本题有三种解法:
第一种: 老实的做两次遍历,第一次遍历得到整个链表数组的大小,然后做减法,求出正序的位置。
第二种: 用vector来直接存储每个item,然后利用vector.size()计算出正序的位置,直接删除。
第三种: 也是最屌的方法。让pre,cur往后走,但忽略n次,也就是只走总次数-n次,这样正好就是走到要删除的位置。
第四种: 使用two pointers, before快after n步,当after==NULL时,before所指的位置正好就是那个位置.
第一种:
1 class Solution { 2 public: 3 ListNode *removeNthFromEnd(ListNode *head, int n) { 4 5 ListNode *fakenode = new ListNode(0); 6 fakenode->next = head; 7 int length = 0; 8 ListNode * p = fakenode; 9 while(p) 10 { 11 length++; 12 p = p->next; 13 } 14 length--; 15 delete p; 16 int cnt = length-n; 17 ListNode *cur = fakenode; 18 while(cnt) 19 { 20 cur=cur->next; 21 cnt --; 22 } 23 if(cur->next) 24 cur->next = cur->next->next; 25 return fakenode->next; 26 } 27 };
第二种:
1 class Solution { 2 public: 3 ListNode *removeNthFromEnd(ListNode *head, int n) { 4 if(head == NULL) 5 return NULL; 6 7 std::vector<ListNode *> v; 8 ListNode *p = head; 9 while(p) 10 { 11 v.push_back(p); 12 p = p->next; 13 } 14 //cout<<v.size(); 15 int position = v.size() - n; 16 if(position == 0) 17 return v[position]->next; 18 else if(position == v.size()-1) 19 v[position-1]->next = NULL; 20 else 21 v[position-1]->next = v[position]->next; 22 return v[0]; 23 24 } 25 };
第三种:
1 class RemoveNthNodeFromEndofList { 2 public: ListNode *removeNthFromEnd(ListNode *head, int n) { 3 if( head == NULL ) { 4 if( n == 0 ) 5 return head; 6 } 7 if( head->next == NULL ) { 8 if( n == 1 ) 9 head = NULL; 10 return head; 11 } 12 ListNode* EndPointer = head; 13 ListNode* Pre = new ListNode(-1); 14 Pre->next = head; 15 ListNode* Cur = head; 16 int DistanceToEnd = 0; 17 while( EndPointer != NULL ) { 18 //cout<<"DistanceToEnd: "<<DistanceToEnd<<" EndPointer->val: "<<EndPointer->val<<endl; 19 if( DistanceToEnd == n ) { 20 Pre = Cur; 21 Cur = Cur->next; 22 } 23 else 24 DistanceToEnd++; 25 EndPointer = EndPointer->next; 26 } 27 if( Cur == head ) 28 head = Cur->next; 29 else 30 Pre->next = Cur->next; 31 return head; 32 } 33 };
                    
                
                
            
        
浙公网安备 33010602011771号