**Input:** head = [1,4,3,2,5,2], x = 3
**Output:** [1,2,2,4,3,5]
**Input:** head = [2,1], x = 2
**Output:** [1,2]
class Solution {
public ListNode partition(ListNode head, int x) {
// edge cases
if (head == null || head.next == null) return head;
//dummy, smallTail, prev, curr
ListNode dummy = new ListNode(Integer.MIN_VALUE);
dummy.next = head;
ListNode smallTail = dummy, prev = dummy, curr = head;
// walk
while (curr != null) {
if (curr.val < x && prev.val >= x) {
// take out
ListNode tmp = curr;
prev.next = curr.next;
curr = curr.next;
// insert
tmp.next = smallTail.next;
smallTail.next = tmp;
smallTail = smallTail.next;
} else {
prev = curr;
curr = curr.next;
if (smallTail.next.val < x) smallTail = smallTail.next;
}
}
return dummy.next;
}
}
// dummy, smallTail, prev, curr
// walk, when val < x, prev.next = curr.next, tmp = curr.
// insert tmp after smallTail
use two dummy node. this one is more concise and less error prone.
class Solution {
public ListNode partition(ListNode head, int x) {
// edge cases
if (head == null || head.next == null) return head;
//dummy, smallTail, prev, curr
ListNode dummy1 = new ListNode(0);
ListNode dummy2 = new ListNode(0);
ListNode curr1 = dummy1, curr2 = dummy2;
// walk
while (head != null) {
if (head.val < x) {
curr1.next = head;
curr1 = curr1.next;
} else {
curr2.next = head;
curr2 = curr2.next;
}
head = head.next;
}
curr2.next = null;
curr1.next = dummy2.next;
return dummy1.next;
}
}