Link: https://leetcode.com/problems/partition-list/

Idea

Create two lists, one for keeping track of nodes with value smaller than x, the other for keeping track of nodes >= x. Then append the great list to the end of small list. Make sure to "un-link" the last node in the great list to avoid cycle.

Code

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode small = new ListNode(0);
        ListNode smallTail = small;
        ListNode large = new ListNode(0);
        ListNode largeTail = large;
        
        while (head != null) {
            if (head.val < x) {
                smallTail.next = head;
                smallTail = smallTail.next;
            } else {
                largeTail.next = head;
                largeTail = largeTail.next;
            }
            
            head = head.next;
        }
        
        smallTail.next = large.next;
        largeTail.next = null;
        return small.next;
    }
}
  • Time: O(n).
  • Space: O(1).