思路:设置两个指针,先让一个指针向前跑n次,然后两个指针同时跑,直到先跑的指针为空,后一个指针就指着需要删掉的元素。注意如果删头结点的时候,需要更改头结点的指针。
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
int count = n;
ListNode *postPointer = head, *prePointer = head, *linkPointer = head;
if(head){
while(count>0){
count--;
postPointer = postPointer->next;
}
while(postPointer){
postPointer = postPointer->next;
linkPointer = prePointer;
prePointer = prePointer->next;
}
if(prePointer == head)
head = prePointer->next;
else
linkPointer->next = prePointer->next;
}
return head;
}
};