双指针解决链表的问题

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;
}
相关推荐
慢云智慧空间4 分钟前
从设备智能到空间理解,空间智能终端解决方案商如何重新定义行业标准
后端
利威尔xu15 分钟前
Go IM 源码实战(13):30 个会话只有 2 个红点,未读数错在三条路径
redis·后端·微服务·面试·golang
薛定谔的猫-菜鸟程序员1 小时前
软件架构设计师开发资料大全(从入门到精通)
后端·python·系统架构·flask·架构设计师
IT_陈寒2 小时前
SpringBoot多环境配置把我坑惨了,这个踩坑经验你最好看看
前端·人工智能·后端
码事漫谈3 小时前
DeepSeek 搞了个 "Super-agent",但不是超级智能
后端
吴凡wudianmei3 小时前
从 0 搭一个 AI Agent(四):SSE 跑通之后,三处“契约错配”与它们的修复边界
前端·后端·aigc
小兔子3 小时前
defer 的参数在写下那一刻就求值了,循环里这样写会踩坑
后端
苍何3 小时前
腾讯 Buddy One 来了,办公生态一键打通 WorkBuddy(附教程)
后端
Tokenfree3 小时前
把通义千问接进工单系统:三个版本够用,但有两个坑没人提前告诉我
后端
wei_shuo3 小时前
MongoDB迁移实战:基于SQL的文档数据开发与多模态融合实践
后端