利用双指针一次遍历实现”找到“并”删除“单链表倒数第K个节点(力扣题目为例)

Problem: 19. 删除链表的倒数第 N 个结点

文章目录

题目描述


思路

1.欲找到倒数第k个节点,即是找到正数的第n-k+1、其中n为单链表中节点的个数 个节点。

2.为实现只遍历一次单链表,我们先可以使一个指针p1指向链表头部再让其先走k步,此时再让一个指针p2指向单链表的头部接着使其同p1一起往后走,当p1指向单链表的尾部空指针时(即p1 = null)时停止,此时p2指向的即为正数n-k+1 个节点也即使倒数第k个节点;

3.但是在单链表的删除 中我们需要找到待删除节点的前驱节点 我们在第二步中只是实现了找到倒数第k个节点 离删除它还差一步,那我们就先找出倒数第k+1个节点再删除倒数第k个节点

复杂度

时间复杂度:

O ( n ) O(n) O(n);

空间复杂度:

O ( 1 ) O(1) O(1)

Code

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // virtual head node
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        dummy.next = head;
        ListNode p = dummy;
        // find the (n + 1) th node from the end
        // then we can remove the n-th node from the end
        ListNode x = findFromEnd(dummy, n + 1);
        // remove the n-th node from the end
        x.next = x.next.next;
        return dummy.next;
    }
    
    // return the k-th node from the end of the linked list
    ListNode findFromEnd(ListNode head, int k) {
        ListNode p1 = head;
        // p1 moves k steps firstly
        for (int i = 0; i < k; ++i) {
            p1 = p1.next;
        }
        ListNode p2 = head;
        // p1 and p2 move n - k steps together
        while (p1 != null) {
            p2 = p2.next;
            p1 = p1.next;
        }
        // p2 is now pointing to the (n - k + 1) -th node,which is the k-th node from the end
        return p2;
    }
}
相关推荐
禹凕10 小时前
滑动窗口算法实战指南
python·算法
DisonTangor10 小时前
【腾讯混元雪耻归来】 Hy4 preview:770B 参数 MoE 旗舰模型,1M 上下文全面开源
人工智能·算法·开源·aigc·腾讯云·腾讯云ai代码助手
明月_清风11 小时前
从二叉树到 B+ 树:一文搞懂工程中「树」的演化之道
数据结构·算法·go
渡我白衣11 小时前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
hetao173383711 小时前
2026-09-01~09-04 hetao1733837 的刷题记录
c++·算法
Evand J12 小时前
【MATLAB例程,图像滤波5】 反谐波均值滑动窗口滤波(CHMF)图像降噪与质量评价,附代码下载链接
图像处理·算法·计算机视觉·matlab·均值算法·滑动窗口滤波·均值滑动
血小板要健康12 小时前
链表 阶段算法总结
java·数据结构·笔记·算法·leetcode·链表
a1879272183112 小时前
【算法】回溯算法(三):三记重锤与 N 皇后——记忆化、状态设计与三层漏斗
算法·leetcode·go·剪枝·回溯·n皇后·算法讲解
HugoStudio_SWAN14 小时前
洛谷 P1420 / P1179 / B4262 最长连号、数字统计与词频统计——统计的三种面孔
c++·学习·程序人生·算法
PFFstronger14 小时前
测试工程师的职业价值
职场和发展