mechanics
mechanics

Reputation: 15

error in creating a linked list using python

I am new to data structures.Tried to create a linkled list with a print function,but when running the program it is throwing an error stating "add_link takes one positional argument but 2 were given".Below is the code.Please help me out. thanks in advance

class node:
    def __init__( self ,value, Next = None):
        self.value = value
        self.Next = None
        newnode = None
    
    def add_link(self,data):
         if(self.Next == None):
              self.Next = node(data)
              newnode = self.Next
         else:
             newnode.Next = node(data)
             newnode = newnode.Next
    
    def print(self):
        if(self.Next !=None):
            print(self.node)
            self.next.print()

 # main         
link = node(10)

link.add_link(20)

link.add_link(30)

link.add_link(40)

link.print()

Upvotes: 1

Views: 84

Answers (2)

Vivek Sable
Vivek Sable

Reputation: 10221

It will be better to create Node as a seprate class/structure, and LinkedList as different.

So that we can implement methods according to class.

class Node:
    """
    @Summary: Node has a set of information and address to the next node.
    """
    def __init__(self, data) -> None:
        self.data = data
        self.next = None


class SinglyLinkedList:
    def __init__(self, item:Node) -> None:
        # Head or start node for Singly Linked List
        self.head = item
             
    def add(self, new_item:Node) -> None:
        """
        @Summary: Adde new item to Singly Linked List
        @Param new_item(Node): New node item
        @Return (None)
        """
        # Check if Linked list is emplty or not.
        if self.head == None:
            self.head = new_item
        else:
            # Add a new item to an end.
            last_node = self.head
            while last_node.next != None:
                last_node = last_node.next
            last_node.next = new_item

    def print(self):
        """Print Linked List"""
        if self.head == None:
            print("No item in Linked list")
        else:
            print("Linked List :")
            tmp_node = self.head
            while True:
                print(tmp_node.data, end=" ")
                if tmp_node.next == None:
                    break
                tmp_node = tmp_node.next
            print()


# Create Node as a Head node. 
item01 = Node(10)
obj = SinglyLinkedList(item01)
obj.add(Node(20))
obj.add(Node(30))
obj.add(Node(40))

obj.print()

Upvotes: 0

Cardstdani
Cardstdani

Reputation: 5223

You need to add self as an argument to the add_link() function:

def add_link(self, data):
     if(self.Next == None):
          self.Next = node(data)
          newnode = self.Next
     else:
         newnode.Next = node(data)
         newnode = newnode.Next

Upvotes: 1

Related Questions