86. Partition List
Problem
Rearrange a linked list so every node with value less than x comes before every node with value ≥ x, keeping the original relative order within both groups.
Example: 1→4→3→2→5→2, x = 3 → 1→2→2→4→3→5
Build two chains (< x and ≥ x) with dummy heads, preserving order, then join them. Terminate the second chain!
Complexity: O(n).
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
small = s = ListNode()
big = b = ListNode()
while head:
if head.val < x:
s.next = s = head
else:
b.next = b = head
head = head.next
b.next = None
s.next = big.next
return small.next
assert list_vals(Solution().partition(make_list([1, 4, 3, 2, 5, 2]), 3)) == [1, 2, 2, 4, 3, 5]
assert list_vals(Solution().partition(make_list([2, 1]), 2)) == [1, 2]
assert list_vals(Solution().partition(make_list([]), 0)) == []
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(), big = new ListNode(), s = small, b = big;
for (; head != null; head = head.next) {
if (head.val < x) s = s.next = head; else b = b.next = head;
}
b.next = null;
s.next = big.next;
return small.next;
}
}
func partition(head *ListNode, x int) *ListNode {
small, big := &ListNode{}, &ListNode{}
s, b := small, big
for ; head != nil; head = head.Next {
if head.Val < x {
s.Next = head
s = head
} else {
b.Next = head
b = head
}
}
b.Next = nil
s.Next = big.Next
return small.Next
}