Problem
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
1 |
|
Explanation
-
The idea is we iterate each element and move all elements that are less than the target before the index of target, so we need to have a
left
boundary, in the leftside of this boundary, all elements are less than target. We also needs to have adummy
node before the head (initallyleft
andpre
points at dummy node). So, we need to create aleft
pointer that points at the end of the list of elements that are less than target. We have acur
pointer that is iterating the elements. We also need apre
pointer. -
For example, when
cur
element is less than target, we need to move thecur
pointer’s value. So first step, thepre.next = cur.next
. Second step,cur.next = left.next
because thecur
’s next element should be the boundary’s right side which isleft.next
. And we need to connect thecur
to the next element of theleft
boundary, so third step,left.next = cur
. After we move the element that is less than target to the end of the boundary, we need to updateleft
andcur
, thepre
stay the same because its next element is already connected to the updatedcur
. -
If the element is not less than target, we can just move
pre
andcur
forward one step. -
The special case is when
left
andpre
point at the same element. If the current element is not less than target, we normally movepre
andcur
one step forward. Else, if the current element is less than target, then from the above’s second stepcur.next = left.next
, in this case,left.next
iscur
, so after we do the second step,cur
is pointing at itself, which is not what we want. To solve this, we can just moveleft
one step forward,pre
andcur
one step forward.
Solution
1 |
|