KatInterview

21. Merge Two Sorted Lists

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to merge two sorted linked lists, list1 and list2, into a single sorted linked list. The new list should be constructed by splicing together the nodes of the original two lists, which means we should reuse the existing nodes rather than creating new ones (except for a potential helper node).

Solution

Merge Two Sorted Lists in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        # Create a dummy node to serve as the start of the merged list.
        # This avoids edge cases for an empty list.
        dummy = ListNode()
        # 'current' will point to the last node of the merged list.
        current = dummy

        # Iterate while both lists have nodes.
        while list1 and list2:
            # Compare the values of the current nodes of both lists.
            if list1.val <= list2.val:
                # If list1's node is smaller or equal, append it.
                current.next = list1
                # Move the pointer of list1 forward.
                list1 = list1.next
            else:
                # If list2's node is smaller, append it.
                current.next = list2
                # Move the pointer of list2 forward.
                list2 = list2.next
            
            # Move the 'current' pointer to the newly added node.
            current = current.next

        # After the loop, at least one of the lists is exhausted.
        # Append the remaining part of the non-exhausted list.
        if list1:
            current.next = list1
        elif list2:
            current.next = list2

        # The merged list starts from the node after the dummy node.
        return dummy.next

Merge Two Sorted Lists in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // Create a dummy node to act as the starting point of the merged list.
        // This simplifies handling of the head of the list.
        ListNode dummy = new ListNode(0);
        // 'current' will be our pointer to build the new list, starting from the dummy node.
        ListNode current = dummy;

        // Traverse both lists as long as there are nodes in both.
        while (list1 != null && list2 != null) {
            // Compare the values of the nodes from both lists.
            if (list1.val <= list2.val) {
                // If list1's node is smaller or equal, link it to our current node.
                current.next = list1;
                // Move the list1 pointer forward.
                list1 = list1.next;
            } else {
                // If list2's node is smaller, link it to our current node.
                current.next = list2;
                // Move the list2 pointer forward.
                list2 = list2.next;
            }
            // Move the 'current' pointer to the end of the merged list.
            current = current.next;
        }

        // At this point, one of the lists is exhausted. 
        // We append the remaining nodes from the other list. 
        // If list1 is not null, it means list2 is exhausted.
        if (list1 != null) {
            current.next = list1;
        }
        // If list2 is not null, it means list1 is exhausted.
        else {
            current.next = list2;
        }

        // The merged list starts after the dummy node.
        return dummy.next;
    }
}

Merge Two Sorted Lists in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        // Create a dummy node to serve as the head of the merged list.
        // This simplifies edge cases like an empty resulting list.
        ListNode* dummy = new ListNode();
        // 'current' will point to the last node in the merged list.
        ListNode* current = dummy;

        // Traverse both lists.
        while (list1 != nullptr && list2 != nullptr) {
            // Compare the values of the two lists' current nodes.
            if (list1->val <= list2->val) {
                // If list1's value is smaller or equal, append it to the merged list.
                current->next = list1;
                // Move to the next node in list1.
                list1 = list1->next;
            } else {
                // If list2's value is smaller, append it to the merged list.
                current->next = list2;
                // Move to the next node in list2.
                list2 = list2->next;
            }
            // Move the 'current' pointer to the new last node.
            current = current->next;
        }

        // After the loop, one of the lists might still have nodes left.
        // Append the remaining part of the non-empty list.
        if (list1 != nullptr) {
            current->next = list1;
        } else {
            current->next = list2;
        }

        // The merged list starts from the node after the dummy node.
        ListNode* mergedHead = dummy->next;
        // Free the memory allocated for the dummy node.
        delete dummy;
        return mergedHead;
    }
};

Merge Two Sorted Lists in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
    // Create a dummy node to act as the head of the new list.
    // This simplifies the logic by providing a node to attach the first element to.
    const dummy = new ListNode(0);
    // 'current' will track the last node in the merged list.
    let current = dummy;

    // Pointers to traverse list1 and list2.
    let p1 = list1;
    let p2 = list2;

    // Loop as long as both lists have nodes.
    while (p1 !== null && p2 !== null) {
        // Compare the values of the current nodes.
        if (p1.val <= p2.val) {
            // If p1's value is smaller or equal, append p1 to the merged list.
            current.next = p1;
            // Move p1 to its next node.
            p1 = p1.next;
        } else {
            // If p2's value is smaller, append p2.
            current.next = p2;
            // Move p2 to its next node.
            p2 = p2.next;
        }
        // Move the 'current' pointer to the newly added node.
        current = current.next;
    }

    // Once one list is exhausted, append the remainder of the other list.
    // If p1 is not null, there are remaining nodes in list1.
    if (p1 !== null) {
        current.next = p1;
    } 
    // If p2 is not null, there are remaining nodes in list2.
    else if (p2 !== null) {
        current.next = p2;
    }

    // The merged list begins at the node after the dummy.
    return dummy.next;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.