Example 1
Input: list1 = 1 → 2 → 4 , list2 = 1 → 3 → 4
Output: 1 → 1 → 2 → 3 → 4 → 4
Output: 1 → 1 → 2 → 3 → 4 → 4
Example 2
Input: list1 = [], list2 = []
Output: []
Output: []
Example 3
Input: list1 = [], list2 = [0]
Output: [0]
Output: [0]
-
Create a new
ListNode with dummy node as head, call it asresult . We are going to attach input list's elements to this list and finally return answer by removing this dummy head. -
Create another temporary
ListNode variable to hold the tail of the resultant list, so that next node comes in order from input lists will be attached to this.
Initialize this withresult from above step as that is the current tail. -
Run a while loop until both input lists are not null.
Now check which node value is less among two input lists, add that to
temp.next and move the pointer to next node for the list which has less value. -
At the end of while,
move temp node to current tail. After adding a node from
list1 orlist2 totemp node, this will become the new tail as highlighted in line 35 in below code. - Repeat this until either of the lists traversal reached to the end.
-
Finally return
result.next , this will remove the dummy head created in step 1 and return the rest.
Complexity Analysis:
Above code runs in O(m + n) time complexity where
Above examples source code can be found on this