To merge several sorted linked lists into one sorted linked list, you can use a similar approach to merging sorted arrays. The idea is to iterate over all the given linked lists and add the smallest head element to a new merged list.
Here's a Python implementation of the algorithm:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
# Create a dummy head node for the merged list
dummy = ListNode(0)
if not lists:
return dummy
# An array to keep track of the indices of current head nodes
pointers = [i for i, list_ in enumerate(lists) if list_]
while pointers:
# Find the smallest value from the current head nodes
smallest_val = min(list_.val for i, list_ in enumerate(lists[pointers]))
# Get the smallest head's index and remove it from the pointers list
smallest_index = next(i for i, _ in enumerate(pointers) if lists[i].val == smallest_val)
# Move the smallest head's pointer to its next node
dummy.next = lists[smallest_index].next
# Update the pointers list and remove the smallest head's index
pointers.remove(smallest_index)
# If the smallest head is empty, remove it from lists
if not lists[smallest_index]:
lists.remove(lists[smallest_index])
# Move the dummy's pointer to the newly added node
dummy = dummy.next
return dummy.next
This function takes in a list of linked lists lists and returns the head of the merged sorted linked list. For a better understanding, you can try running it with different test cases and comparing the result with a manually created merged linked list.