Search code examples
pythonsingly-linked-list

Linked List Implementation Error In Python


So I was trying to make a Linked List in python, but I'm getting this error:

If currentNode.nextNode is None:

AttributeError: 'str' object has no attribute 'nextNode'

Not sure why I get that as currentNode.nextNode should have a .nextNode attribute just like every other node.

Here's the code:

class linkedListNode:
    def __init__(self, value, nextNode=None):
        self.value=value 
        self.nextNode=nextNode 
    
class linkedList():
    def __init__(self, head=None):
        self.head=head 

    def insert(self, value):

        node=linkedListNode(value)

        if self.head==None:
            self.head=node
            return 

        currentNode = self.head 

        while True:
            if currentNode.nextNode is None:
                currentNode.nextNode=node
                break
            currentNode = currentNode.nextNode

    def printLinkedList (self):
        curNode=self.head 
        while curNode!=None:
            print(curNode.value) 
            curNode=curNode.nextNode


#Just testing out the linked list below to see if it works:

ll=linkedList("10")
ll.insert("50")
ll.insert(4)
ll.insert(6)
ll.insert(3)
ll.insert(1)        
ll.printLinkedList()

Solution

  • The way you defined linkedList, it expects an instance of linkListNode as an argument, not a value.

    ll = linkedList(linkedListNode("10"))