双指针解决链表的问题

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;
}
相关推荐
码事漫谈13 分钟前
国产时序数据库崛起:金仓凭什么在复杂场景中碾压InfluxDB
后端
上进小菜猪18 分钟前
当时序数据不再“只是时间”:金仓数据库如何在复杂场景中拉开与 InfluxDB 的差距
后端
盖世英雄酱581361 小时前
springboot 项目 从jdk 8 升级到jdk21 会面临哪些问题
java·后端
程序猿DD2 小时前
JUnit 5 中的 @ClassTemplate 实战指南
java·后端
Victor3562 小时前
Netty(14)如何处理Netty中的异常和错误?
后端
Victor3563 小时前
Netty(13)Netty中的事件和回调机制
后端
码事漫谈3 小时前
VS Code 1.107 更新:多智能体协同与开发体验升级
后端
码事漫谈4 小时前
从概念开始开始C++管道编程
后端
@淡 定4 小时前
Spring中@Autowired注解的实现原理
java·后端·spring