Reputation: 799
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.
Upvotes: 2
Views: 742
Reputation: 726809
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 next
pointers of its elements to make the list sorted.
You will need three pointers - newHead
, head1
, and head2
.
head1
and head2
to the head
of the original listhead2
until you see a break in the sorted sequence (i.e. when head2->next->value
is less than head2->value
). Cut the list there by setting head2->next
to NULL
; keep the original head2->next
- it is your new head2
At this point, you have two independently ordered, separate linked lists, and you can apply the classic merge algorithm. Set newHead
to the smaller element of head1
or head2
, and then move in a loop, setting the next
pointer of the current last element to the smaller of head1
or head2
. Once you hit head1->next == NULL
or head2->next == NULL
, assign the head of the other list to the next
of the list that ran out of elements first. You are done - newHead
now points to the beginning of a sorted list.
Upvotes: 4