This somehow reminds me of my answer to the question of the Dutch national flag .
After I thought that this is what I came to, let's see if this works out. I suppose the main problem is the merge phase of the merge in O(1)
extra-space.
Our view of the linked list:
[ 1 ] => [ 3 ] => [ 2 ] => [ 4 ] ^head ^tail
As a result, you will complete this merge step:
[ 1 ] => [ 3 ] => [ 2 ] => [ 4 ] ^p ^q ^tail
Be p
and q
pointers for the segments we want to combine.
Just add your nodes after the tail
pointer. If *p <= *q
you add p
to the tail.
[ 1 ] => [ 3 ] => [ 2 ] => [ 4 ] => [ 1 ] ^p ^pp ^q/qq ^tail ^tt
Otherwise add q
.
[ 1 ] => [ 3 ] => [ 2 ] => [ 4 ] => [ 1 ] => [ 2 ] ^p ^pp ^q ^qq/tail ^tt
(Keeping track of the end of our q
list becomes complicated)
Now, if you move them, you will quickly lose information about where you are. You can beat this with a smart way to move pointers or add lengths to the equation. I definitely prefer the latter. The approach becomes as follows:
[ 1 ] => [ 3 ] => [ 2 ] => [ 4 ] ^p(2) ^q(2) ^tail
[ 3 ] => [ 2 ] => [ 4 ] => [ 1 ] ^p(1) ^q(2) ^tail
[ 3 ] => [ 4 ] => [ 1 ] => [ 2 ] ^p(1) ^q(1) ^tail
[ 4 ] => [ 1 ] => [ 2 ] => [ 3 ] ^p(0)/q(1) ^tail
[ 1 ] => [ 2 ] => [ 3 ] => [ 4 ] ^q(0) ^tail
Now you can use the extra O(1)
space to move your elements.