友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

92. 反转链表 II

给你单链表的头指针 head 和两个整数 leftright,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表

示例 1:

0092 01
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]

示例 2:

输入:head = [5], left = 1, right = 1
输出:[5]

提示:

  • 链表中节点数目为 n

  • 1 <= n <= 500

  • -500 <= Node.val <= 500

  • 1 <= left <= right <= n

进阶: 你可以使用一趟扫描完成反转吗?

思路分析

将链表拆分成三段(注意保存必要的访问节点):

  • 第一段,保存原有的顺序不变;

  • 第二段,保存反转的链表;

  • 第三段,保存反转后的链表;

最后再将三个拼接在一起。

  • 一刷

  • 二刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List II.
 * Memory Usage: 36.6 MB, less than 11.36% of Java online submissions for Reverse Linked List II.
 *
 * @author D瓜哥 · https://www.diguage.com
 * @since 2020-02-05 22:46
 */
public ListNode reverseBetween(ListNode head, int m, int n) {
    if (m == n) {
        return head;
    }
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode tail = dummy;
    ListNode reverseList = new ListNode(0);
    ListNode reverseTail = null;
    for (int i = 1; i <= n && Objects.nonNull(head); i++) {
        ListNode next = head.next;
        if (i < m) {
            tail = head;
        } else {
            if (i == m) {
                reverseTail = head;
            }
            ListNode rNext = reverseList.next;
            reverseList.next = head;
            head.next = rNext;
        }
        head = next;
    }
    if (Objects.nonNull(reverseTail)) {
        reverseTail.next = head;
    }
    tail.next = reverseList.next;
    return dummy.next;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2025-04-10 21:33:16
 */
public ListNode reverseBetween(ListNode head, int m, int n) {
  if (m == n) {
    return head;
  }
  ListNode dummy = new ListNode(0);
  dummy.next = head;
  ListNode pre = dummy;
  int a = m;
  while (a > 1) {
    pre = head;
    head = head.next;
    a--;
  }
  pre.next = null;
  ListNode[] result = reverse(head, null, n - m + 1);
  head.next = result[1];
  pre.next = result[0];
  return dummy.next;
}

private ListNode[] reverse(ListNode head, ListNode pre, int n) {
  if (head == null) {
    return new ListNode[]{pre, null};
  }
  if (n == 1) {
    ListNode next = head.next;
    head.next = pre;
    return new ListNode[]{head, next};
  }
  ListNode[] result = reverse(head.next, head, n - 1);
  head.next = pre;
  return result;
}

思考题

尝试递归的解题方式。