📜  门| GATE-CS-2004 |问题 25(1)

📅  最后修改于: 2023-12-03 15:42:15.795000             🧑  作者: Mango

GATE-CS-2004 Problem 25

This problem is related to linked lists. Given two sorted singly linked lists, merge them to form a single sorted linked list.

Inputs

The inputs to the program are two linked lists where each node contains an integer value and a pointer to the next node. The pointers are null for the last node in each list.

Outputs

The output of the program is a single linked list containing all the elements of the input lists in sorted order.

Solution

The solution to this problem is to traverse both input linked lists simultaneously. Take the smaller value of the two current nodes and make that the next node in the output list. Repeat until all input nodes have been processed.

Pseudo code
mergeLists(head1, head2)
    if head1 is null, return head2
    if head2 is null, return head1
    if head1.value <= head2.value
        head1.next = mergeLists(head1.next, head2)
        return head1
    else
        head2.next = mergeLists(head1, head2.next)
        return head2
Complexity

The time complexity of this algorithm is O(n + m) where n and m are the lengths of the input linked lists.

The space complexity of this algorithm is O(n + m) due to the recursive calls.

Example
Input:

LinkedList 1: 1 -> 3 -> 7 -> 9 -> null

LinkedList 2: 2 -> 4 -> 6 -> 8 -> null

Output:

LinkedList 3: 1 -> 2 -> 3 -> 4 -> 6 -> 7 -> 8 -> 9 -> null

Code
public class ListNode {
    int val;
    ListNode next;
    
    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class MergeTwoSortedLinkedLists {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } 
        if (l2 == null) {
            return l1;
        }
        if (l1.val <= l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}