DEV Community

Mubashir
Mubashir

Posted on

Merging Sorted Linked List

In this task, I worked on merging two sorted linked lists into a single sorted linked list. This problem helped me understand how linked lists work and how to handle pointers efficiently.

What I Did:
I created a function mergeTwoLists that takes two sorted linked lists as input and merges them into one sorted list.
Example:
List1: 1 → 3 → 5

List2: 2 → 4 → 6

Output: 1 → 2 → 3 → 4 → 5 → 6
How I Solved It:
To solve this problem, I used a dummy node technique to simplify handling the head of the new list.
Step-by-step approach:
I created a dummy node to act as the starting point of the merged list
Used a pointer called tail to keep track of the last node in the merged list
Compared nodes from both lists:
If list1.val <= list2.val, I attached list1 node
Otherwise, I attached list2 node
Moved the pointer (tail) forward each time
Continued this until one list becomes empty
Final Step:
If any nodes are left in either list, I attached them directly to the end

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def mergeTwoLists(self, list1, list2):
        dummy = ListNode(-1)
        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

        # attach remaining nodes
        if list1:
            tail.next = list1
        else:
            tail.next = list2

        return dummy.next 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)