leetcode-19
1 class Solution { 2 public: 3 ListNode* removeNthFromEnd(ListNode* head, int n) { 4 ListNode *start=new ListNode(0); 5 start->next=head; 6 ListNode *pre=start,*curr=start; 7 for(int i=0;i<n;i++){ 8 curr=curr->next; 9 } 10 while(curr->next!=NULL){ 11 pre=pre->next; 12 curr=curr->next; 13 } 14 ListNode *tmp=pre->next; 15 pre->next=pre->next->next; 16 delete tmp; 17 return start->next; 18 } 19 };
典型的快慢指针问题,不过要记得delete,以免内存泄漏