1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 10 class Solution 11 { 12 public: 13 ListNode* removeNthFromEnd(ListNode* head, int n) 14 { 15 ListNode *pre=head,*beh=head; //after operation,pre is the previous node of which node we want to delete 16 int count=1; 17 while(count<=n) //fixed the distance between pre and beh 18 { 19 beh=beh->next; 20 count++; 21 } 22 if(beh==NULL) //if n is equal to the length of linklist,delete first node 23 return head->next; 24 while(beh->next!=NULL) //when beh reach to the last node,pre is the previous node of n(th) node from end of list 25 { 26 pre=pre->next; 27 beh=beh->next; 28 } 29 beh=pre->next; 30 pre->next=pre->next->next; //delete pre->next 31 free(beh); 32 return head; 33 } 34 };
用两个指针,指针之间相距n,当快指针跑到链表末尾时,慢指针正好指向倒数第n个节点的前一个节点,删除pre的下一个节点即可