Home > Software engineering >  Linked List, can't acess the data from NEXT NODE
Linked List, can't acess the data from NEXT NODE

Time:11-05

My problem is at the display function, I can't access the value cur_node.data which is a reference to node.next.data. I'm new to python and I'm trying to learn Linked LISTS, this code is from an old VIDEO which is why it probably isn't working

My code below:

class node:
    def __init__(self,data=None):
        self.data =data
        self.next = None

class linkedlist:
    def __init__(self):
        self.head = node()
    def append(self,data):
        new_node  = node(data)
        cur = self.head
        while cur.next!=None:
            cur = cur.next
        cur.next = new_node
    def lenght(self):
        count = 0
        start = self.head
        while start.next!=None:
            count =1
            start =  start.next
        return count
    def display(self):
        elements = []
        cur_node = self.head
        while cur_node !=None:
            cur_node = cur_node.next 
            elements.append(cur_node.data)   # here at cur_node.data its not accessing DATA from the NODE 
            
        print(elements)

if __name__ =='__main__':
    pass
li = linkedlist()
li.append(5)
li.append(5)
li.display()

it's expected to display the array made of the nodes at the display() function

CodePudding user response:

Fala Brazuca,

The problem is with your while condition.

while cur_node != None
   cur_node = cur_node.next

See carefully,

Linked list

When your loop is iterating on the last element, cur_node still have data on it, but its next element does not.

What your code is saying is -> If the last element has data, then assume a None type, which doesn't have an attribute called data. Therefore, causing the AttributeError.

elements.append(cur_node.data)

AttributeError: 'NoneType' object has no attribute 'data'

This is easily solved by especifying that the NEXT element can't be None.

Final result:

def display(self):
    elements = []
    cur_node = self.head
    while cur_node.next != None:
        cur_node = cur_node.next
        elements.append(cur_node.data)
            
    print(elements)
  • Related