题目:
Given a linked list, remove the nth node from the end of list and return its head.
设置两个结点pre,post,先走的结点pre走n步,然后两个结点一起走,当pre到达末尾的时候
post->next恰好是要删除的结点
注意两个陷阱
1.设置pre 和 post的next为head,是为了【1】,1 即删除 链表中仅有的一个元素的情况
2.post->next=post->next->next 而不是post->next=pre 出现这个问题的原因是当你思考思路的时候
假设代入的是2,不小心就会得出post->next=pre的结论
总结: 当涉及删除remove元素的时候,设置结点要设置在头结点之前,避免只存在一个结点情况
大部分算法的陷阱都是边界条件考虑不清楚
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head==NULL) return NULL;
ListNode *pre=new ListNode(-1);
pre->next=head;
ListNode *post=pre;
ListNode *p=post;
for(int i=0;i<n;i++){
pre=pre->next;
}
while(pre&&pre->next){
pre=pre->next;
post=post->next;
}
post->next=post->next->next;
return p->next;
}
};