Error: Merge two sorted linkedlist using dummy head technique in Python


I’m trying to solve merge two sorted linkedlist problem using dummy head technique. For some reason I have an error coming from passing an argument to my dummy head holder. The output suppose to merge both linkedlist like this: 1-> 1-> 2-> 3-> 7-> None

I would be happy if you please guide which data needs to pass in my dummy head variable? Thanks in advance! This is the error I have:

    dummy = LinkedList()
TypeError: __init__() missing 1 required positional argument: 'data

Here’s my complete code:

class LinkedList:
    def __init__(self, data): = data = None

def print_list(head: LinkedList) -> None:
    while head:
        print(, end=" -> ")
        head =

def merge_lists(headA, headB):
    dummy = LinkedList()
    curr = dummy

    while headA != None and headB != None:
        if <
   = headA
            headA =
   = headB
            headB =

        curr =

    if headA != None: = headA
    else: = headB


node1 = LinkedList(1) = LinkedList(2) = LinkedList(7)

node2 = LinkedList(1) = LinkedList(3)

print(merge_lists(node1, node2)) # 1-> 1-> 2-> 3-> 7-> None


Since it is a dummy node, and you never ever use the data attribute of that node, you can pass anything as argument, like None:

dummy = LinkedList(None)

Alternatively, you could specify that providing an argument is optional, and define the constructor as follows:

class LinkedList:
    def __init__(self, data=None): = data = None

Unrelated, but at the end of your script you have:

print(merge_lists(node1, node2))

This will print the object reference. You probably wanted to call the function you have defined for this purpose:

print_list(merge_lists(node1, node2))

If you want print to work like that, then instead of the print_list function, enrich LinkedList with an __iter__ method to ease iteration over the values in the list, and a __repr__ or __str__ method as follows:

class LinkedList:
    def __init__(self, data=None): = data = None

    def __iter__(self):
        head = self
        while head:
            head =
        yield None  # Optional

    def __repr__(self):
        return " -> ".join(map(str, self))

…and then you can do

print(merge_lists(node1, node2))

Answered By – trincot

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published