Logo for ammarahmed.ca
Easy
Jul 24, 2025
#linked-list
#sorting

21. Merge Two Sorted Lists

Problem

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into 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:

1Input: list1 = [1,2,4], list2 = [1,3,4] 2Output: [1,1,2,3,4,4] 3

Example 2:

1Input: list1 = [], list2 = [] 2Output: [] 3

Example 3:

1Input: list1 = [], list2 = [0] 2Output: [0] 3

Constraints:

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

        Approach

        We can start off by creating a dummy list node that will store our resultant list in it's next pointer. Then, we take a pointer to it as the tail of our list. We also initialize pointers for list1 and list2.

        We start by iterating while the list1 and list2 pointers are not nil. We check the values for them and whichever is less, we set the tail's next pointer to a new node with that value and move the tail pointer to the new node. We also move the pointer for the list that we took the value from to its next node.

        When we complete the iteration, there may be one list that we haven't iterated through fully so we check both pointers and if either of them is not nil, we set the tail's next pointer to the remaining nodes of that list.

        Finally, we return the next pointer of the dummy node which contains our created head of the merged list.

        Complexity

        Time: O(n)

        We iterate through both lists once, where n is the total number of nodes in both lists combined.

        Space: O(1)

        No extra space is used except for the resultant list which is not accounted for in the analysis.

        Solution

        1func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { 2 dummy := &ListNode{} 3 tail := dummy 4 curr1, curr2 := list1, list2 5 for curr1 != nil && curr2 != nil { 6 var v int 7 if curr1.Val <= curr2.Val { 8 v = curr1.Val 9 curr1 = curr1.Next 10 } else { 11 v = curr2.Val 12 curr2 = curr2.Next 13 } 14 tail.Next = &ListNode{ Val: v } 15 tail = tail.Next 16 } 17 if curr2 != nil { 18 tail.Next = curr2 19 } 20 if curr1 != nil { 21 tail.Next = curr1 22 } 23 return dummy.Next 24} 25