Merge Sorted Linked List
Last updated
Last updated
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
The time complexity of the algorithm is O(n + m), where n and m are the lengths of the two input linked lists. This is because each node in both linked lists is visited exactly once.
The space complexity of the algorithm is O(1). This is because the algorithm only uses a constant amount of space to store the dummy node and the pointers (tail
, list1
, list2
), regardless of the size of the input linked lists. The algorithm modifies the input linked lists in-place and does not use any additional data structures whose size depends on the input. Hence, the space complexity is constant.