LeetCode 21. Merge Two Sorted Lists

Description

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []
Output: []

Example 3:

Input: l1 = [], l2 = [0]
Output: [0]

Constraints:

• The number of nodes in both lists is in the range [0, 50].
• -100 <= Node.val <= 100
• Both l1 and l2 are sorted in non-decreasing order.

Explanation

We compare the pointer to l1, l2 linked list node one by one. The smaller list node would be added to the new linked list.

Java Solution

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode l3 = dummy;

while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
l3.next = l1;
l1 = l1.next;
} else {
l3.next = l2;
l2 = l2.next;
}
l3 = l3.next;
}

if (l1 != null) {
l3.next = l1;
}

if (l2 != null) {
l3.next = l2;
}

return dummy.next;
}
}

Python Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:

l3 = ListNode(0)
dummy = l3
while l1 != None and l2 != None:
if l1.val <= l2.val:
new_node = ListNode(l1.val)
l1 = l1.next
else:
new_node = ListNode(l2.val)
l2 = l2.next

l3.next = new_node
l3 = new_node

while l1 != None:
new_node = ListNode(l1.val)
l3.next = new_node
l3 = new_node
l1 = l1.next

while l2 != None:
new_node = ListNode(l2.val)
l3.next = new_node
l3 = new_node
l2 = l2.next

return dummy.next

• Time Complexity: O(N)
• Space Complexity: O(

5 Thoughts to “LeetCode 21. Merge Two Sorted Lists”

1. Em says:

Thank you, Good Techer!
Looking foward to your next video.

1. GoodTecher says:

Thank you for support!