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
leftboundary, in the leftside of this boundary, all elements are less than target. We also needs to have adummynode before the head (initallyleftandprepoints at dummy node). So, we need to create aleftpointer that points at the end of the list of elements that are less than target. We have acurpointer that is iterating the elements. We also need aprepointer. -
For example, when
curelement is less than target, we need to move thecurpointer’s value. So first step, thepre.next = cur.next. Second step,cur.next = left.nextbecause thecur’s next element should be the boundary’s right side which isleft.next. And we need to connect thecurto the next element of theleftboundary, 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 updateleftandcur, theprestay the same because its next element is already connected to the updatedcur. -
If the element is not less than target, we can just move
preandcurforward one step. -
The special case is when
leftandprepoint at the same element. If the current element is not less than target, we normally movepreandcurone 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.nextiscur, so after we do the second step,curis pointing at itself, which is not what we want. To solve this, we can just moveleftone step forward,preandcurone step forward.
Solution
1 | |