Loading content...
You are provided with the head nodes of two singly linked lists, sequence1 and sequence2, where both lists are arranged in ascending (non-decreasing) order.
Your task is to merge these two linked lists into a single unified linked list that preserves the ascending order. The resulting merged list should be constructed by interweaving the nodes from both original lists—you should reuse the existing nodes rather than creating new ones.
Return the head node of the newly combined linked list.
A linked list is a linear data structure where each element (node) contains a value and a reference (pointer) to the next node in the sequence. Unlike arrays, linked lists do not store elements in contiguous memory locations, which makes certain operations like insertion and deletion more efficient.
When merging two sorted linked lists, you need to compare the values at the current positions of both lists and select the smaller value to add to the result list. This process continues until all nodes from both lists have been processed.
Both input lists are already sorted in non-decreasing order, which means you can use a simple comparison-based merge strategy.
Either or both lists can be empty (null/None), and your solution should handle these edge cases gracefully.
The merge should be done in-place by rearranging the existing node pointers, not by creating a completely new list with copied values.
The relative order of equal elements should be preserved—if both lists have nodes with the same value, you can choose either one first, but maintaining stability (taking from the first list first) is a good practice.
list1 = [1,2,4]
list2 = [1,3,4][1,1,2,3,4,4]We merge the two sorted lists node by node. Starting from the heads: 1 ≤ 1, so we take 1 from list1. Then 2 > 1, so we take 1 from list2. Continuing: 2 < 3, take 2. Then 4 > 3, take 3. Finally, 4 = 4, take 4 from list1, then 4 from list2. The resulting merged list is [1,1,2,3,4,4].
list1 = []
list2 = [][]Both input lists are empty, so the merged result is also an empty list.
list1 = []
list2 = [0][0]The first list is empty, so the merged result is simply the second list [0].
Constraints