双指针解决链表的问题

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;
}
相关推荐
苏三说技术4 分钟前
消息积压了100万,除了加机器,还能干什么?
后端
CN_山居17 分钟前
Ubuntu使用Google Authenticator(MFA)
后端
小猪乔治爱打球18 分钟前
[Golang 修仙之路] 场景题:红包系统设计
后端·面试
程序猿二饭18 分钟前
SpringBoot 实现支持多个微信小程序的登录
后端
AlpsMonaco19 分钟前
kubernetes(k8s)集群迁移更新
后端
华仔啊20 分钟前
刚学 Java 就被内存溢出劝退?这 10 个集合内存管理技巧救了我!
java·后端
武子康25 分钟前
大数据-90 Spark RDD容错机制:Checkpoint原理、场景与最佳实践 容错机制详解
大数据·后端·spark
花花无缺28 分钟前
python自动化-pytest-标记
后端·python
Villiam_AY1 小时前
使用 chromedp 高效爬取 Bing 搜索结果
后端·爬虫·golang
CryptoPP1 小时前
跨境金融数据对接实践:印度NSE/BSE股票行情API集成指南
开发语言·后端·金融