Merge Sorted Linked List

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.

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode MergeTwoLists(ListNode list1, ListNode list2) {
         ListNode dummyNode = new ListNode(0);
        ListNode tail = dummyNode;
        while (true)
        {
            if (list1 == null)
            {
                tail.next = list2;
                break;
            }
            if (list2 == null)
            {
                tail.next = list1;
                break;
            }
            if (list1.val <= list2.val)
            {
                tail.next = list1;
                list1 = list1.next;
            }
            else
            {
                tail.next = list2;
                list2 = list2.next;
            }

            tail = tail.next;
        }
        return dummyNode.next;
    }
}

The time complexity of the algorithm is O(n + m), where n and m are the lengths of the two input linked lists. This is because each node in both linked lists is visited exactly once.

The space complexity of the algorithm is O(1). This is because the algorithm only uses a constant amount of space to store the dummy node and the pointers (tail, list1, list2), regardless of the size of the input linked lists. The algorithm modifies the input linked lists in-place and does not use any additional data structures whose size depends on the input. Hence, the space complexity is constant.

Last updated