双指针解决链表的问题

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;
}
相关推荐
JS菌10 分钟前
AI Agent 沙箱双层防护体系:从权限过滤到内核隔离的完整实现
前端·人工智能·后端
IT空门:门主1 小时前
Spring 注入三剑客:@Resource、@Autowired、@RequiredArgsConstructor 到底该用哪个?
java·后端·spring
ServBay1 小时前
云端 AI 蜜月期宣告结束,为什么 2026 年开发者转向本地优先架构
后端·ai编程
IT_陈寒1 小时前
Vite这个坑我帮你踩了,动态导入居然这样才生效
前端·人工智能·后端
Sam_Deep_Thinking1 小时前
Spring Boot 的启动原理是什么?
java·spring boot·后端
南部余额2 小时前
Spring WebClient 从入门到精通
java·后端·spring
摇滚侠2 小时前
Spring 零基础入门到进阶 基于注解管理 Bean 38-43
xml·java·后端·spring·intellij-idea
SamDeepThinking2 小时前
我们当年是如何真实落地BFF的?
java·后端·架构
Asmewill2 小时前
Centos系统docker时间同步方案
后端
用户8356290780512 小时前
使用 Python 操作 Word 评论和回复
后端·python