DEV Community

Anjana R.K.
Anjana R.K.

Posted on • Edited on

Merge Two Sorted Linked Lists

Hi everyone!
Today I solved a classic linked list problem where we merge two sorted lists into one sorted list. It’s simple but very important for interviews.

Problem
Given two sorted linked lists, merge them into a single sorted linked list.
Example:
Input: list1 = [1,2,4], list2 = [1,3,4]

Output: [1,1,2,3,4,4]

My Approach
At first, I thought of copying values into a new list, but that’s unnecessary.
Instead:

We can directly link nodes from both lists

Logic
Create a dummy node (to simplify handling)
Compare nodes from both lists:
Attach the smaller one
Move forward in that list
After loop, attach remaining nodes

Code (Python)
class Solution:
def mergeTwoLists(self, list1, list2):
dummy = ListNode(0)
tail = dummy

    while list1 and list2:
        if list1.val <= list2.val:
            tail.next = list1
            list1 = list1.next
        else:
            tail.next = list2
            list2 = list2.next

        tail = tail.next

    if list1:
        tail.next = list1
    else:
        tail.next = list2

    return dummy.next
Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity
Time: O(n + m)
Space: O(1) (no extra list)

Key Insight
Using a dummy node makes the code cleaner and avoids edge cases.

What I Learned
Linked list problems become easier with dummy nodes
Always reuse nodes instead of creating new ones
This concept is used in merge sort as well

Thanks for reading!
Feel free to share your thoughts or alternative approaches.

Top comments (0)