Leeuw
Leeuw

Reputation: 53

Nonetype has no attribute 'next' in linked list

I'm stuck, I can't see what is the problem in my code. here it is:

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

class LinkedList: 
  def __init__(self,head=None):
    self.head = head

  def append(self,data):
    new_Node = Node(data)
    if (self.head):
      cons = self.head
      while(cons):
        cons = cons.next
      cons.next = new_Node  
    else:
      self.head = new_Node
  def printt(self):
    cons = self.head
    while(cons):
      print(cons.data)
      cons = cons.next
Q = LinkedList()
Q.append(3)
Q.append(4)
Q.printt()

and the error msg is

  Traceback (most recent call last):
  File "/tmp/sessions/18c2fb2c9abeb710/main.py", line 26, in <module>
    Q.append(4)
  File "/tmp/sessions/18c2fb2c9abeb710/main.py", line 16, in append
    cons.next = new_Node  
AttributeError: 'NoneType' object has no attribute 'next' 

I tried to fix the error but failed to solve it. Please can you help?

Upvotes: 2

Views: 149

Answers (2)

Dr. V
Dr. V

Reputation: 1914

All you need is to change the line :

while(cons):

to -

while(cons.next):

because otherwise, cons is already None when you leave the loop.

Upvotes: 1

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You are getting error in the line :

while(cons):

You have to stop when cons.next is None. In your case, you code will run till cons becomes None. Then on the next line, you have the statement cons.next = new_Node, which essentially checks None.next and hence the error.

So use cons.next instead of just cons. The following will work fine -

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

class LinkedList: 
  def __init__(self,head=None):
    self.head = head

  def append(self,data):
    new_Node = Node(data)
    if (self.head):
      cons = self.head
      while(cons.next):
        cons = cons.next
      cons.next = new_Node  
    else:
      self.head = new_Node
  def printt(self):
    cons = self.head
    while(cons):
      print(cons.data)
      cons = cons.next
Q = LinkedList()
Q.append(3)
Q.append(4)
Q.printt()

Upvotes: 1

Related Questions