我的方法就是用2个指针,一开头都指向head。当第1个指针往后移动到n+1的时候,带动第2个指针往后移动。当第1个指针到尾后,第2个指针就指向要删掉的那个节点的前一个节点。
注意:
1) 有可能刚好要删掉的那个节点是head (acc==n的情况)。
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head) return NULL;
int acc=0;
ListNode* p1=head;
ListNode* p2=head;
while(p1) {
if (acc++>n) p2=p2->next;
p1=p1->next;
}
//here p2 actually points to the previous node of the deleted node.
if (acc==n){
ListNode* temp=head;
head=head->next; temp->next=NULL; return head;
}else{
ListNode* temp=p2->next;
p2->next=p2->next->next;
temp->next=NULL;
return head;
}
}
int main()
{
ListNode a(1),b(2),c(3),d(4),e(5);
a.next=&b;
b.next=&c;
c.next=&d;
d.next=&e;
ListNode*p=removeNthFromEnd(&a, 2);
while(p){
cout<<p->val<<" ";
p=p->next;
}
return 0;
}