双指针解决链表的问题

1. 背景

双指针解决链表相关的问题,基本都是中等难度

  1. 删除链表的倒数第 N 个结点
  2. 旋转链表

2. 方案

leetcode 19

ini 复制代码
public ListNode removeNthFromEnd(ListNode head, int n){
    ListNode second = head;
    ListNode first = head;
    for (int i = 0; i < n; i++) {
        first = first.next;
    }
    if (first == null){
        return head.next;
    }
    while(first.next != null){
        first = first.next;
        second = second.next;
    }
    second.next = second.next.next;
    return head;

}

leetcode 61

ini 复制代码
public ListNode rotateRight(ListNode head, int k){
    if (head == null || head.next == null){
        return head;
    }
    ListNode temp = head;
    int lens = 1;
    while (temp.next != null){
        lens ++;
        temp = temp.next;
    }
    k = k % lens;
    ListNode first = head;
    ListNode second = head;
    int idx = 0;
    while(first.next != null){
        if (idx ++ < k){
            first = first.next;
        } else {
            first = first.next;
            second = second.next;
        }
    }
    first.next = head;
    head = second.next;
    second.next = null;
    return  head;
}
相关推荐
随风,奔跑19 小时前
Spring Cloud Alibaba(六)-链路追踪SkyWalking
java·后端·spring·skywalking
铁皮饭盒19 小时前
成为AI全栈 - 第1课:后端到底是干嘛的?一张图拆解登录
前端·后端·ai编程
Flynt19 小时前
LangGraph 生产环境跑了三个月,我的真实感受
后端
Rust语言中文社区19 小时前
【Rust日报】2026-04-28 Pacquet:pnpm 的 Rust 重写版本
开发语言·后端·rust
胡马北风Norstead19 小时前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 7)
后端
fliter20 小时前
Cloudflare 防火墙规则背后的工程实践
后端
JarvanMo20 小时前
搞懂这 5 个 AI 术语,你就超过了 90% 的人
前端·后端
IT_陈寒20 小时前
Vite的HMR怎么突然失效了?原来是我太年轻
前端·人工智能·后端
胖纳特20 小时前
Nextcloud 文件预览困局与破局:集成 BaseMetas Fileview 实现全格式在线预览
前端·后端
lczllx20 小时前
MIT 6.824-lab3A(实现思路)
后端