19. Remove Nth Node From End of List

题目:

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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值