面试题 02.04. 分割链表

题目

给你一个链表的头节点 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

题解

public ListNode partition(ListNode head, int x) {
    // 小于x部分
    ListNode left = new ListNode(0);
    // 左指针
    ListNode leftCursor = left;
    // 大于x部分
    ListNode right = new ListNode(0);
    // 右指针
    ListNode rightCursor = right;
    while (head != null) {
        if (head.val < x) {
            leftCursor.next = new ListNode(head.val);
            leftCursor = leftCursor.next;
        } else {
            rightCursor.next = new ListNode(head.val);
            rightCursor = rightCursor.next;
        }
        head = head.next;
    }
    // 拼接左右链表
    leftCursor.next = right.next;

    return left.next;
}