In a written test I came across a question which reads as follows:
We are given an integer linked list of which both first half and second half are sorted independently. Write a function to merge the two parts to create one single sorted linked list.
Constraint: do not use any extra space.
Test Cases and output:
Input List1 :
4->5->6->7->1->2->3;
Output :
1->2->3->4->5->6->7
Input 2:
5->6->7->8->1->2->3->4;
Output 2 :
1->2->3->4->5->6->7->8
What I can think of is by using two pointers: one for the first half traversal and one for the second half traversal. Using them I can traverse from head to middle (using 1st pointer) and from middle to last (using 2nd Pointer). While traversing both parts simultaneously, I can compare values and swap when needed.
But this solution employs use of two pointers which consumes memory.
Can it be done without using any memory?
As it was a written test, I cannot ask for clarifications.
Assistance is appreciated. Thanks.
When they say “do not use extra space”, they do not mean pointers and scalars; they do mean “arrays” and “dynamically allocated structures”. In your case, the amount of memory is fixed.
Merging two ordered lists is simple: first, cut the list in half, and then re-arrange
nextpointers of its elements to make the list sorted.You will need three pointers –
newHead,head1, andhead2.head1andhead2to theheadof the original listhead2until you see a break in the sorted sequence (i.e. whenhead2->next->valueis less thanhead2->value). Cut the list there by settinghead2->nexttoNULL; keep the originalhead2->next– it is your newhead2At this point, you have two independently ordered, separate linked lists, and you can apply the classic merge algorithm. Set
newHeadto the smaller element ofhead1orhead2, and then move in a loop, setting thenextpointer of the current last element to the smaller ofhead1orhead2. Once you hithead1->next == NULLorhead2->next == NULL, assign the head of the other list to thenextof the list that ran out of elements first. You are done –newHeadnow points to the beginning of a sorted list.