双指针解决链表的问题

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;
}
相关推荐
AskHarries18 小时前
用户埋点怎么设计
后端
极客悟道18 小时前
VS Code + JetTUI 开发 Spring Boot项目,教程来了
后端
Yeauty18 小时前
自建 HLS 第一问:fMP4 还是 TS?用 Rust 在进程内把两种都跑出来
开发语言·后端·rust
Zane199419 小时前
copy 和 deepcopy 到底在拷贝什么?一文讲清赋值、浅拷贝、深拷贝的引用关系
后端·python
zhiSiBuYu051719 小时前
Flask 路由新手入门与实战指南
后端·python·flask
元界metalite19 小时前
禁止 Feign!我们为什么自研 InternalServiceClient
后端
用户1257585243619 小时前
进销存后台别急着上线,先重放一次退货请求
人工智能·后端·go
qq_225891746619 小时前
基于Python的城市内涝积涝监测数据可视化分析系统
后端·python·信息可视化·数据分析·django
苏三说技术19 小时前
为什么越来越多人用Apache Tika?
后端
Zane199419 小时前
Lock 接口与 AQS 核心原理:手写理解一把可重入锁是怎么运作的
java·后端