Partition list

problem [https://leetcode.com/problems/partition-list/ 86. Partition List]

Problem description
Given the  of a linked list and a value , partition it such that all nodes less than   come before nodes greater than or equal to.

You should preserve the original relative order of the nodes in each of the two partitions.


 * Example 1
 * Input: head = [1,4,3,2,5,2], x = 3
 * Output: [1,2,2,4,3,5]


 * Example 2
 * Input: head = [2,1], x = 2
 * Output: [1,2]

Analysis
We can maintain two temporary lists: one for the elements smaller than target, the other for elements greater than equal to target. Using two dummy heads makes the things easier.
 * Smaller-than list: (dummy head) → …
 * Greater-or-equal list: (dummy head) → …

Then we can use a single pointer  to scan through each element in the original linked list. Depending on the value of this pointer, we can join the tail of the corresponding temporary list to the pointer node, and update the tail of that list accordingly.
 * This works because although we are modifying existing nodes in-place, every time when we append to one of the temporarily lists by changing the  pointer, the tail node of that list must have already been visited by the   pointer. Hence, the   pointer will go over all the nodes of the lists in the original order, and visit each node exactly once.

After scanning through all the elements, we can join the two temporary lists together.
 * 1) Join the tail of the smaller-than list to the head (next of dummy head) of the greater-than-or-equal list.
 * 2) Set the   pointer of the tail of greater-than-or-equal list to  . This step is necessary to prevent the joined list from forming cycles.

Time complexity

 * We need to go over each node in the original list exactly once. This results in O(1) time complexity of the whole algorithm.

Auxiliary space complexity
Temporary variables on stack:
 * Stack
 * The two dummy heads.
 * The two marker pointers in the two temporary lists, which are used to append nodes to them.
 * The  pointer to scan through the original linked list.

So the auxiliary space complexity on stack is O(1).


 * Heap: We have just allocated the two dummy heads on the heap. So the auxiliary space complexity on heap is O(1).


 * Add them up: The total auxiliary space complexity is O(1).