Statement▼
You are given an array, lists, containing k singly linked lists. Each of these linked lists is individually sorted in ascending order.
Your task is to merge all k linked lists into a single sorted linked list in ascending order and return the merged list.
Constraints:
k== lists.length0≤ k≤103 0≤ lists[i].length≤500 −103≤ lists[i][j]≤103 Each
lists[i]is sorted in ascending order.The sum of all
lists[i].lengthwill not exceed103 .
Solution
This approach uses a divide-and-conquer method to merge multiple sorted lists into a single sorted list. It initially pairs up the lists and merges each pair. This merging of pairs produces
Using the intuition above, we implement the algorithm as follows:
Check if the input
listsis non-empty. If it is:Initialize a variable
stepto1to control the merging interval.While
stepis less than the number of lists, start the pairwise merging process:Iterate through the list indices from
0tolen(lists) - step, with increments ofstep * 2:For each index
i, merge the two lists at positionsiandi + stepusing themerge_2_listshelper function.Replace the list at index
iwith the merged result.
After finishing one pass of pairwise merges, double the
stepvalue to prepare for the next level of merging.
After the outer loop terminates, return the final list stored at
lists[0].
The merge_2_lists helper function takes the heads of two linked lists, head1 and head2, and merges the two lists as follows:
Create a
dummynode to serve as the starting point of the merged list.Initialize a pointer,
prev, starting at thedummynode to track where to attach the next node.While both input lists are non-empty:
Compare the current nodes,
head1andhead2, and append the smaller node to the merged list usingprev.next.Move the pointer in the selected list forward.
Advance the
prevpointer.
Once one of the lists is exhausted, attach the remaining nodes from the other list to the merged list.
Return the merged list starting at
dummy.next, which skips the placeholderdummynode.
Let’s look at the following illustration to get a better understanding of the solution: