利用快慢指针来解决此问题 ,具体代码如下.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast=head;
ListNode* cur=new ListNode(0); cur->next=head;
ListNode* slow=cur;
for(int i=0;i<n;i++)fast=fast->next;
while(fast)
{
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return cur->next;
}
};