MERGE TWO LINKED LISTS

Merge Two Sorted Linked Lists – Recursive Approach

Introduction

In this problem, we are given two sorted linked lists. The goal is to merge them into a single sorted linked list by rearranging the existing nodes.

This problem helps in understanding linked list traversal and recursion.

Problem Statement

Given two sorted linked lists list1 and list2:

  • Merge them into one sorted list

  • Do not create new nodes unnecessarily

  • Return the head of the merged list

Example

Input:

list1 = [1, 2, 4]
list2 = [1, 3, 4]

Output:

[1, 1, 2, 3, 4, 4]

Solution Code

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {

        if(list1 != null && list2 != null){
            if(list1.val < list2.val){
                list1.next = mergeTwoLists(list1.next, list2);
                return list1;
            }
            else{
                list2.next = mergeTwoLists(list1, list2.next);
                return list2;
            }
        }

        if(list1 == null)
            return list2;

        return list1;
    }
}

Approach Used: Recursion

Idea

At each step, we compare the current nodes of both lists:

  • Choose the smaller node

  • Recursively merge the remaining lists

How It Works

  1. Base condition:

    • If one list is empty = return the other list

  2. Compare values:

    • If list1.val < list2.val:

      • Attach list1 node

      • Recursively merge the rest

    • Else:

      • Attach list2 node

      • Recursively merge the rest

  3. Continue until all nodes are merged

Why This Approach Was Chosen

  • Code is clean and easy to understand

  • No need for extra data structures

  • Uses the natural recursive structure of linked lists

Alternative Approach

  • Iterative method (using loop)
     Avoids recursion stack
     Slightly more code

Why recursion here?
Because it makes the logic shorter and more intuitive.

Time and Space Complexity

  • Time Complexity: O(n + m)
    (n = length of list1, m = length of list2)

  • Space Complexity: O(n + m)
    (due to recursion stack)

Important Observation

  • We are not creating new nodes, just reusing existing ones

  • This is called in-place merging

  • The structure of linked list naturally fits recursion

Edge Cases

  • Both lists empty = return null

  • One list empty = return the other

  • Lists with duplicate values = handled correctly

Conclusion

The recursive approach provides a clean and elegant solution to merge two sorted linked lists. By comparing nodes step by step and building the result recursively, we efficiently merge both lists while maintaining sorted order.

 

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT