【Java】【LeetCode】19. Remove Nth Node From End of List

本文介绍了一种使用双指针技术在一次遍历中删除链表倒数第N个节点的方法。通过实例演示了如何实现这一操作,并提供了完整的代码示例。

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

题目:

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

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.

Follow up:

Could you do this in one pass?

题解:

这道题也是经典题,利用的是fast和slow双指针来解决。

首先先让fast从起始点往后跑n步。

然后再让slow和fast一起跑,直到fast==null时候,slow所指向的node就是需要删除的节点。

注意,一般链表删除节点时候,需要维护一个prev指针,指向需要删除节点的上一个节点。

代码如下:

public class RemoveNthFromEndofList
{

    public static void main(String[] args)
    {
        /**
         * Given a linked list, remove the n-th node from the end of list and return its head.
         * 
         * Example:
         * 
         * Given linked list: 1->2->3->4->5->6->7, and n = 3.
         * 
         * After removing the second node from the end, the linked list becomes 1->2->3->4->6->7.
         * Note:
         * 
         * Given n will always be valid.
         * 
         * Follow up:
         * 
         * Could you do this in one pass?
         */
        ListNode ln1 = new ListNode(1);
        ListNode ln2 = new ListNode(2);
        ListNode ln3 = new ListNode(3);
        ListNode ln4 = new ListNode(4);
        ListNode ln5 = new ListNode(5);
        ListNode ln6 = new ListNode(6);
        ListNode ln7 = new ListNode(7);
        ln1.next = ln2;
        ln2.next = ln3;
        ln3.next = ln4;
        ln4.next = ln5;
        ln5.next = ln6;
        ln6.next = ln7;
        LeetCodeUtil.printNodeList(removeNthFromEnd(ln1, 3)); // 1->2->3->4->6->7.
        LeetCodeUtil.printNodeList(removeNthFromEnd(ln1, 1)); // 1->2->3->4->6.
        LeetCodeUtil.printNodeList(removeNthFromEnd(ln1, 5)); // 2->3->4->6.
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值