Table of contents
Question
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a 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.
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]
Explanation
So we've got head of two sorted linked lists, now we need to return a single sorted linked list, it's quite simple task if you know basics of linked list, A singly linked list have two fields, one is for value and other one is for address of next node, we traverse node to node using the address field of the node.
Here we'll used another linked list to store our sorted list.
we'll traverse through the given linked lists till any one of them doesn't point to null, now if list1.data <= list2.data
then we'll add list1
to our list else add list2
and increase the pointer of our list pointer.
At last check if any one of the list is not pointing to null and add that list to our list.
Code -
Recursive
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode head = new ListNode();
ListNode tail = head;
if (l1.val <= l2.val){
tail.next = l1;
l1.next = mergeTwoLists(l1.next, l2);
} else {
tail.next = l2;
l2.next = mergeTwoLists(l1,l2.next);
}
tail = tail.next;
return head.next;
}
Time Complexity
- O(n+m), as we're traversing both the Lists.
Space Complexity
- O(n+m), recursive stack space.
Iterative
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode();
ListNode tail = head;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
tail.next = list1;
list1 = list1.next;
} else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}
tail.next = list1 != null ? list1 : list2;
return head.next;
}
Time Complexity
- o(n + m)
Space Complexity
- O(1)