LeetCode 19 : Remove Nth Node From End of List

本文介绍两种高效算法来解决链表中倒数第N个节点的删除问题。第一种方法通过两次遍历来确定待删除节点的位置;第二种方法采用双指针技巧,在一次遍历中实现目标。这两种方法在实际应用中都具有较高的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种方法:先遍历一遍取得长度,然后长度减去n就知道要删除正着数第几个节点,注意,我这里一直卡在,想找到要删除的第len-n个,只能循环cur=cur->next;len-n-1遍,才能将cur指针刚好指在要删除的节点的前一个。所以就会有两种情况会不进
 for(int i=1;i<=len-n-1;i++)
            cur=cur->next;

循环,第一种要删除的是正数第一个并且满足len=n,返回head->next就行;第二种是要删除的是正数第二个(此时cur指向head)可以和其他情况一起删除,利用

  cur->next=cur->next->next;

因此完整代码如下,Runtime: 9 ms You are here! Your runtime beats 93.79 % of cpp submissions.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int len=0;
        ListNode *cur=head;
        while(cur!=NULL)
        {
            len++;
            cur=cur->next;
        }
        cur=head;
        for(int i=1;i<=len-n-1;i++)
            cur=cur->next;
        if(cur==head&&n==len)
         return head->next;   
        cur->next=cur->next->next;
        return head;
    }
};

第二种方法:用两个指针,一个快指针先走n步,一个慢指针从头开始走,这样当快指针走到尾部的时候,慢指针所指的就是要删除元素的前一个元素。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *first=head;
        for(int i=1;i<=n;i++)
            first=first->next;
        if(first==NULL)
            return head->next;
        ListNode *second=head;
        while(first->next!=NULL)
        {
            first=first->next;
            second=second->next;
        }
        
        second->next=second->next->next;
        return head;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值