19. Remove Nth Node From End of List (LL)

本文介绍了一种算法来解决链表中删除倒数第N个节点的问题。通过使用双指针技巧,首先将两个指针都指向链表头部,然后其中一个指针向前移动N步,之后两个指针同时移动直到第一个指针到达链表尾部前一个位置,此时第二个指针恰好指向待删除节点的前一个节点,从而实现删除操作。

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

 1 class Solution {
 2    public ListNode removeNthFromEnd(ListNode head, int n) {
 3        if(head == null) return head;
 4        if(head.next == null) return null;
 5        ListNode node1 = head;
 6        ListNode node2 = head;
 7        ListNode p = node1;
 8        for(int i = 0; i < n - 1; i++) {
 9            node2 = node2.next;
10        }
11        if(node2.next == null) {   //要加上这一段 要是node2刚好到tail 下面代码无法更新node1, 因为node1在head
12            return head.next;
13        }
14        while(node2.next != null) {
15            p = node1;
16            node1 = node1.next;
17            node2 = node2.next;
18        }
19        p.next = node1.next;
20        return head;
21    }
22 }

 

转载于:https://www.cnblogs.com/goPanama/p/9496015.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值