双指针解决链表的问题

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;
}
相关推荐
两点王爷12 小时前
SpringBoot 项目集成 GeoServer 源码,实现地图服务发布
java·spring boot·后端
leoZ23113 小时前
2026-09-09-springboot-cloud-deploy-pitfalls
java·前端·javascript·vue.js·人工智能·spring boot·后端
海上彼尚14 小时前
Cursor 模型的强度实测排行
前端·人工智能·后端
GoGeekBaird15 小时前
从「跑完即销毁」到「用完再销毁」:云沙箱的一次进化
后端·github·ai编程
孫治AllenSun15 小时前
【LangChain4J-09】开发学习知识点
spring boot·后端·学习
lisin-lee-cooper16 小时前
简单聊聊 Spring 框架源码
java·后端·spring
复方金银花颗粒16 小时前
reactor和proactor的好处和坏处。为什么要用reactor而不用 proactor?
后端·信号处理
IT_陈寒16 小时前
JavaScript的这个隐式转换特性差点让我加班到凌晨
前端·人工智能·后端
用户83562907805117 小时前
使用 Python 在 Excel 中添加和编辑形状
后端·python