双指针解决链表的问题

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;
}
相关推荐
会编程的吕洞宾11 分钟前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
技术小代11 分钟前
弹窗里的 RegionName 为什么不生效?把区域作用域和模块化一次讲明白|MVVM框架-Prism-3
后端
斯维赤14 分钟前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
程序员cxuan1 小时前
上海团队开源了首个国产记忆模型,554B!这也太狠了
人工智能·后端·程序员
天天鸭2 小时前
前端转全栈,要学会后端看项目的思维
前端·后端·ai编程
BingoGo2 小时前
为什么 PHP 应该只保留 ZTS 构建模式
后端·php
孟陬2 小时前
Foobar 技术周刊 #161:AI 录屏员工屏幕训练 SOP,被当做「动物园的猴子」是否触犯隐私?
前端·后端·程序员
SimonKing2 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
Rain的Java大神之路3 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
mldong4 小时前
换审批人不用写代码:jeeflow工作流引擎内置 9 种找人规则
后端·架构