python-3.xdata-structureslinked-list

Single LinkedList


Currently doing my self studies/research about the Data Structure and Algorithm. I came with this tutorial.

I listen carefully on his lecture. However, when I'm implementing his code to my jupyter notebook. I got an error saying "AttributeError: type object 'Node' has no attribute 'value' "

This is the code:

class Node:
    def __init__(self, value= None):
        self.value = value
        self.next = None  # -------------------------> O(1)

class SLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
    def __iter__(self):
        node = self.head
        while node:
            yield node
            node = node.next
    # insert in linked list
    def insertSLL(self, value, location):
        newNode = Node(value)
        if self.head is None:
            self.head = newNode
            self.tail = newNode
        else:
            if location == 0:
                newNode.next = self.head
                self.head = newNode
            elif location == 1:
                newNode.next = Node 
                self.tail.next = newNode 
                self.tail = newNode
            else:
                tempNode = self.head
                index = 0
                while index < location - 1:
                    tempNode = tempNode.next
                    index += 1
                nextNode = tempNode.next
                tempNode.next = newNode
                newNode.next = nextNode
                if tempNode == self.tail:
                    self.tail = newNode


singlyLinkedList = SLinkedList()
singlyLinkedList.insertSLL(1, 1)
singlyLinkedList.insertSLL(2, 1)
singlyLinkedList.insertSLL(3, 1)
singlyLinkedList.insertSLL(4, 1)

singlyLinkedList.insertSLL(0, 0)
singlyLinkedList.insertSLL(0, 3)

print([node.value for node in singlyLinkedList])


Hoping someone could explain, why it is not working now?


Solution

  • Your issue lies in this block of code:

    elif location == 1:
        newNode.next = Node
        self.tail.next = newNode 
        self.tail = newNode
    

    The problem is that you're setting newNode.next equal to Node, which isn't correct. next should remain undefined in this case.

    The corrected code should look like this:

    elif location == 1:
        self.tail.next = newNode 
        self.tail = newNode
    

    This way, newNode.next is not incorrectly assigned, ensuring proper linked list behavior.