双指针解决链表的问题

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;
}
相关推荐
Code blocks10 分钟前
GB28181视频服务wvp部署(一)
java·spring boot·后端
我命由我1234516 分钟前
Spring Boot - Spring Boot 静态资源延迟响应(使用拦截器、使用过滤器、使用 ResourceResolver)
java·spring boot·后端·spring·java-ee·intellij-idea·intellij idea
华仔啊1 小时前
3 分钟让你彻底搞懂 Spring 观察者和发布者模式的本质区别
java·后端
言之。1 小时前
LiteLLM:让LLM调用变得简单统一
后端·python·flask
驰羽1 小时前
[GO]golang接口入门:从一个简单示例看懂接口的多态与实现
开发语言·后端·golang
ZhengEnCi1 小时前
Python_try-except-finally 完全指南-从异常处理到程序稳定的 Python 编程利器
后端·python
程序员小假2 小时前
我们来说一说 Redisson 的原理
java·后端
白衣鸽子2 小时前
数据库高可用设计的灵魂抉择:CAP权衡
数据库·后端
xyy1232 小时前
SixLabors.ImageSharp 使用指南
后端