双指针解决链表的问题

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;
}
相关推荐
To_OC8 小时前
从一行入口代码啃透 NestJS:工厂模式、装饰器和依赖注入是怎么串起来的
后端·设计模式·nestjs
Python私教8 小时前
多个项目怎么安全合并?先适配,再切换
后端·python·架构
Python私教10 小时前
从表格到管理系统:别先写页面,先补齐权限、流程和审计
数据库·后端·架构
北斗落凡尘10 小时前
LangGraph 入门实战(12)--使用MCP
后端·python·langchain
SomeB1oody12 小时前
【RustyML入门】6.0. 数学工具
开发语言·后端·机器学习·rust·教程
IT_陈寒12 小时前
为什么我的JavaScript闭包总是漏掉那个变量?
前端·人工智能·后端
用户83562907805113 小时前
如何使用 Python 将 PowerPoint 转换为 PDF 文档
后端·python
倔强的石头_13 小时前
从 8 行报错到一条故障链:我用蓝耘 MaaS 做了一个 AI 日志分析助手
后端
敲个大西瓜13 小时前
Spring Could Alibaba 核心面试题
java·后端·spring
用户83562907805113 小时前
如何使用 Python 为 PowerPoint 幻灯片添加切换效果
后端·python