LeetCode 21. Merge Two Sorted Lists

Description

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

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

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

            

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

Leave a Reply to Em Cancel reply

Your email address will not be published. Required fields are marked *