1 class Solution { 2 public: 3 ListNode* removeNthFromEnd(ListNode* head, int n) { 4 if(n<=0||head==NULL) return head; 5 ListNode prehead(0); 6 prehead.next=head; 7 ListNode *p=head; 8 int length=0,i; 9 while(p->next) 10 { 11 length++; 12 p=p->next; 13 } 14 p=&prehead; 15 length++; 16 if(n>length)n=n%length; 17 i=length-n; 18 19 while(i--)p=p->next; 20 if(n==1) p->next=NULL; 21 else p->next=p->next->next; 22 return prehead.next; 23 } 24 };
效率不高,还是以前的思路,没有创新,下面是别人的一个比较好的
1 class Solution { 2 public: 3 ListNode* removeNthFromEnd(ListNode* head, int n) { 4 if(n<=0||head==NULL) return head; 5 ListNode prehead(0); 6 prehead.next=head; 7 ListNode *p=&prehead; 8 head=&prehead; 9 while(n--) 10 { 11 p=p->next; 12 } 13 while(p->next) 14 { 15 p=p->next; 16 head=head->next; 17 } 18 head->next=head->next->next; 19 20 return prehead.next; 21 } 22 };
凡是说倒着第几个都可以利用顺着的第几个打个标记,然后另一个从头开始,这个继续直到这个到结尾。