双指针解决链表的问题

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;
}
相关推荐
世界哪有真情30 分钟前
用虚拟IP扩容端口池:解决高并发WebSocket端口耗尽问题
前端·后端·websocket
知其然亦知其所以然38 分钟前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
武子康41 分钟前
大数据-30 ZooKeeper Java-API 监听节点 创建、删除节点
大数据·后端·zookeeper
知了一笑42 分钟前
SpringBoot3集成多款主流大模型
spring boot·后端·openai
wmze44 分钟前
InnoDB存储引擎--索引与锁
后端
星辰大海的精灵1 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
调试人生的显微镜1 小时前
iOS App首次启动请求异常调试:一次冷启动链路抓包与初始化流程修复
后端
AI小智1 小时前
Context Engineering:AI 工程的下一个前沿阵地?
后端
paopaokaka_luck1 小时前
基于SpringBoot+Vue的酒类仓储管理系统
数据库·vue.js·spring boot·后端·小程序
梦兮林夕1 小时前
02 gRPC 语法及类型介绍
后端·go·grpc