📌  相关文章
📜  国际空间研究组织 | ISRO CS 2013 |问题 8(1)

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

ISRO CS 2013 - Question 8

In this question, we are given two linked lists. We need to write a function that merges them and returns the combined linked list. The merged list should be in ascending order.

Problem Analysis

We are given two linked lists List1 and List2. We need to write a function that merges them and returns the merged linked list. The merged list should contain all the elements of both List1 and List2, and should be in ascending order.

Solution

We can solve this problem using a simple algorithm. We start by creating a new linked list called mergedList. We then traverse both List1 and List2 simultaneously. At each step, we compare the current elements of both lists and add the smaller one to mergedList. We repeat this process until we have traversed both lists completely.

Once we have merged both lists, we need to return the head of mergedList. The final linked list will have all the elements of List1 and List2, and will be in ascending order.

Pseudo Code
Node mergeLists(Node l1, Node l2) {
    Node dummy = new Node(0);
    Node curr = dummy;
    
    while (l1 != null && l2 != null) {
        if (l1.data <= l2.data) {
            curr.next = l1;
            l1 = l1.next;
        } else {
            curr.next = l2;
            l2 = l2.next;
        }
        curr = curr.next;
    }
    // add remaining elements
    if (l1 != null) {
        curr.next = l1;
    }
    if (l2 != null) {
        curr.next = l2;
    }
    return dummy.next;
}
Time Complexity

The algorithm has to traverse both linked lists, so the time complexity is O(n+m) where n and m are the lengths of List1 and List2 respectively.

Space Complexity

We are creating a new linked list mergedList, which requires additional space. The space complexity is therefore O(n+m) where n and m are the lengths of List1 and List2 respectively.

Conclusion

In this question, we have seen how to merge two linked lists. We created a new linked list mergedList and traversed both List1 and List2 simultaneously. At each step, we compared the current elements of both lists and added the smaller one to mergedList. We returned the head of mergedList, which contained all the elements of List1 and List2 in ascending order.