Leetcode:19. Remove Nth Node From End of List

本文介绍了一道链表操作的经典题目——删除链表倒数第N个节点,并给出了两种解法:一种是通过计算链表长度再定位删除,另一种是使用双指针技巧实现单次遍历删除。

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

0X01 题目

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

  • Given n will always be valid.
  • Try to do this in one pass.

0X02 题意

题目比较简单,给定一个链表和一个数字n,从链表中删除倒数第n个元素。

0X03 题解

1.解法一(Cathy:C++)

yyj的解法,大致思路就是先用一个循环求出链表的总长度m,然后再根据n找到需要删除的元素,删除即可。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if ((head == NULL) or (head->next == NULL))
        {
            return NULL;
        }

        int m = 1;
        ListNode* lc;
        lc = head->next;
        while (lc != NULL)
        {
            m++;
            lc = lc->next;
        }
        if (n == m)
        {
            return head->next;
        }

        lc = head;
        int i = 0;
        while (i < m - n - 1)
        {
            lc = lc->next;
            i++;
        }
        lc->next = lc->next->next;
        return head;
    }
};

2.解法二(Dante:Java)

我第一反应想出来的方法,最初有一些边界值没考虑到位,被Leetcode干掉了,然后加了一个头指针就解决了。

大致思路就是有两个指针fast和slow,fast比slow的位置早n个,然后开始循环,当slow指向最后一个元素的时候,slow就找到了该被删除的元素。

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode start = new ListNode(0);
        ListNode slow = start, fast = start;
        slow.next = head;
        for(int i=1; i<=n+1; i++)   {
            fast = fast.next;
        }
        while(fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return start.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值