Example 1
Input: list1 = 1 → 2 → 4 , list2 = 1 → 3 → 4
Output: 1 → 1 → 2 → 3 → 4 → 4
Example 2
Input: list1 = [], list2 = []
Output: []
Example 3
Input: list1 = [], list2 = [0]
Output: [0]
Solution public class MergeTwoSortedLists { static class ListNode { int element; ListNode next; public ListNode (int element) { this.element = element; } } public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode result = new ListNode(0);// create a new ListNode with a dummy head ListNode temp = result; // purpose of this temp List is to hold the tail of ListNode while (list1 != null || list2 != null) { if(list1 == null) { temp.next = list2; break; } if(list2 == null) { temp.next = list1; break; } if(list1.element <= list2.element) { temp.next = new ListNode(list1.element); list1 = list1.next; } else if (list1.element > list2.element) { temp.next = new ListNode(list2.element); list2 = list2.next; } temp = temp.next; // for the next iteration update the tail to current tail } return result.next; // return result by removing teh dummy head created in step-1 } }
Complexity Analysis:

Above code runs in O(m + n) time complexity where m is the size of the input list1 and n is the size of the input list2, as we are looping through the input lists only one time. Space complexity is O(n) that is taken by the result list.

Above examples source code can be found on this GitHub link for Java code and JUnit tests can be found under GitHub link for Unit tests code

Similar Articles

  1. Merge Two Sorted Linked Lists And Remove Duplicates