19. Remove Nth Node From End of List

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *temp=head;
        int count=0;
        while(temp)
        {
            count++;
            temp=temp->next;
        }
        int del=count-n+1;
        ListNode *prenode=new ListNode(-1);
        ListNode *pre=prenode;
        pre->next=head;
        temp=head;
        count=1;
        while(temp) {
            if (count == del) {
                pre->next = pre->next->next;
                break;
            }
            pre=temp;
            temp=temp->next;
            count++;
        }
        return prenode->next;
    }
};

这是第二种解决方法 整个过程只需要遍历一遍 当后指针指向n+2个节点的时候 前指针指向第一个数 当后指针为null的时候 前指针指向倒数第n个节点的前驱节点。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(!head)
            return head;

        ListNode *prehead=new ListNode(-1);
        if(!head->next&&n==1)
            return NULL;
        prehead->next=head;
        ListNode *first=NULL;
        ListNode *tail=prehead;
        int count=1;
        while(tail)
        {
            if(count==n+2)
            {
                first=prehead;
            }
            tail=tail->next;
            count++;
            if(first)
                first=first->next;
        }
        if(count==n+2)
        {
            first=prehead;
        }
        first->next=first->next->next;
        return prehead->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hebastast

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值