双指针解决链表的问题

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;
}
相关推荐
isysc114 分钟前
面了一个校招生,竟然说我是老古董
java·后端·面试
uhakadotcom25 分钟前
静态代码检测技术入门:Python 的 Tree-sitter 技术详解与示例教程
后端·面试·github
幂简集成explinks31 分钟前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
River41635 分钟前
Javer 学 c++(十三):引用篇
c++·后端
RoyLin43 分钟前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
爱海贼的无处不在1 小时前
一个需求竟然要开14个会:程序员的日常到底有多“会”?
后端·程序员
IT_陈寒2 小时前
Java 性能优化:5个被低估的JVM参数让你的应用吞吐量提升50%
前端·人工智能·后端
南囝coding2 小时前
《独立开发者精选工具》第 018 期
前端·后端
绝无仅有2 小时前
数据库MySQL 面试之死锁与排查经验总结
后端·面试·github