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

Issue

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):
        self.data = data
        self.next = None


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


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

    while headA != None and headB != None:
        if headA.data < headB.data:
            curr.next = headA
            headA = headA.next
        else:
            curr.next = headB
            headB = headB.next

        curr = curr.next

    if headA != None:
        curr.next = headA
    else:
        curr.next = headB

    return dummy.next



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


node2 = LinkedList(1)
node2.next = LinkedList(3)

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

Solution

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):
        self.data = data
        self.next = 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):
        self.data = data
        self.next = None

    def __iter__(self):
        head = self
        while head:
            yield head.data
            head = head.next
        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