Leetcode Merge Two Sorted Lists problem solution in Python programming

In the Leetcode Merge Two Sorted Lists problem solution in Python programming You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Leetcode Merge Two Sorted Lists problem solution in Python programming

class Solution(object):
    def mergeTwoLists(self, list1, list2):
        if not list1: return list2
        if not list2: return list1
        
        dummy = prev = ListNode(-1)
        dummy.next = list1
        n1, n2 = list1, list2
        
        while n1 and n2:
            if n1.val < n2.val:
                if not n1.next: n1.next = n2; break
                prev, n1 = n1, n1.next
            else:
                tmp = n2.next
                prev.next = n2
                n2.next = n1
                prev = n2
                n2 = tmp
        
        return dummy.next

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *