归档

86. 分隔链表

86. 分隔链表

题目

描述:

给你一个链表的头节点 head 和一个特定值 x,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你应当 保留 两个分区中每个节点的初始相对位置。

示例 1:

示例1图片

  • 输入: head = [1,4,3,2,5,2], x = 3
  • 输出: [1,2,2,4,3,5]

示例 2:

  • 输入: head = [2,1], x = 2
  • 输出: [1,2]

提示:

  • 链表中节点的数目在范围 [0, 200] 内
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

题解

用两条链分别收集节点

题目要求按 < x 和 >= x 分成两组,并保留每组内部的原顺序。例如 [1,4,3,2,5,2]、x = 3,小值组应为 [1,2,2],大值组应为 [4,3,5],最后拼成 [1,2,2,4,3,5]。

建立两个虚拟头节点 smallDummy 和 largeDummy,分别指向两组的起点;small、large 则指向各组当前的尾节点。遍历原链表,把当前节点接到对应尾部,再更新尾指针。因为节点按照原访问顺序进入各组,所以相对顺序不会改变。

这里复用的是原节点,没有复制它们。两个虚拟头节点只用于简化空分组的处理,不属于最终结果。

拼接前先切断旧后继

遍历结束后先执行 large.next = null,再令 small.next = largeDummy.next,最后返回 smallDummy.next。大值组的尾节点可能仍保留原链表中的后继,必须把这条旧连接清除。

以上例为例,大值组尾节点 5 原本指向最后一个 2;而这个 2 在拼接后会指向大值组的头 4。如果不把 5 的后继置空,就会形成 4 → 3 → 5 → 2 → 4 的环。

核心代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public ListNode partition(ListNode head, int x) {
    ListNode smallDummy = new ListNode(0);
    ListNode largeDummy = new ListNode(0);
    ListNode small = smallDummy, large = largeDummy;

    while (head != null) {
        if (head.val < x) {
            small.next = head;
            small = small.next;
        } else {
            large.next = head;
            large = large.next;
        }
        head = head.next;
    }

    large.next = null;
    small.next = largeDummy.next;
    return smallDummy.next;
}

如果某组为空,其尾指针仍指向虚拟头节点,上述拼接仍然成立;空链表也会返回 null。完整示例中的 smallHead、largeHead 对应这里的两个虚拟头节点。

每个节点只处理一次,时间为 $O(n)$。只新增两个虚拟头节点及固定数量的指针,辅助空间为 $O(1)$。

完整示例

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public class Main {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static ListNode partition(ListNode head, int x) {
        ListNode smallHead = new ListNode(0);
        ListNode small = smallHead;
        ListNode largeHead = new ListNode(0);
        ListNode large = largeHead;
        while (head != null) {
            if (head.val < x) {
                small.next = head;
                small = small.next;
            } else {
                large.next = head;
                large = large.next;
            }
            head = head.next;
        }
        large.next = null;
        small.next = largeHead.next;
        return smallHead.next;
    }
    public static ListNode createList(int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]);
        ListNode curr = head;
        for (int i = 1; i < arr.length; i++) {
            curr.next = new ListNode(arr[i]);
            curr = curr.next;
        }
        return head;
    }
    public static void printList(ListNode head) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        ListNode curr = head;
        while (curr != null) {
            sb.append(curr.val);
            if (curr.next != null) {
                sb.append(", ");
            }
            curr = curr.next;
        }
        sb.append("]");
        System.out.println(sb.toString());
    }
    public static void main(String[] args) {
        int[] arr1 = {1, 4, 3, 2, 5, 2};
        int x1 = 3;
        ListNode head1 = createList(arr1);
        System.out.println("示例 1 输入:");
        System.out.print("head = ");
        printList(head1);
        System.out.println("x = " + x1);
        ListNode res1 = partition(head1, x1);
        System.out.print("示例 1 输出: ");
        printList(res1);
        System.out.println("-----------------------------");
        int[] arr2 = {2, 1};
        int x2 = 2;
        ListNode head2 = createList(arr2);
        System.out.println("示例 2 输入:");
        System.out.print("head = ");
        printList(head2);
        System.out.println("x = " + x2);
        ListNode res2 = partition(head2, x2);
        System.out.print("示例 2 输出: ");
        printList(res2);
    }
}

运行结果(OpenJDK 21.0.12):

1
2
3
4
5
6
7
8
9
示例 1 输入:
head = [1, 4, 3, 2, 5, 2]
x = 3
示例 1 输出: [1, 2, 2, 4, 3, 5]
-----------------------------
示例 2 输入:
head = [2, 1]
x = 2
示例 2 输出: [1, 2]
本文由作者按照 CC BY 4.0 进行授权