0

I do not know why I am getting the AttributeError: 'NoneType' object has no attribute 'data' when running pop

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

    class stack:
        def __init__(self):
            self.top = None
        def push(self,p):
            new_node = PersonNode(p)
            if self.top == None:
                self.top = new_node
            else:
                new_node.next = self.top
                self.top = new_node
        def pop(self):
            # if self.top != None:
            #     print("{0} is popped successfully".format(self.top.data))
                #self.top = self.top.next
                curr_node = self.top
                while curr_node != None:
                    curr_node = curr_node.next
                    #self.top = curr_node.next
                    print(curr_node.data, "is popped successfully")
3
  • Because you try to access curr_node.data after going to the next node, and you haven't tested if it is None or not. Just invert the last two lines. Commented May 3, 2020 at 17:16
  • I did, but now the while loop keeps indefinitely, how to break the loop by making curr_node = None after the last item? Commented May 3, 2020 at 17:22
  • This is how I am calling the function: while (stack.top != None): stack.pop() Commented May 3, 2020 at 17:48

2 Answers 2

1

Change

while curr_node != None:
   curr_node = curr_node.next
   #self.top = curr_node.next
   print(curr_node.data, "is popped successfully")

to

while curr_node.next != None:
   curr_node = curr_node.next

print(curr_node.data, "is popped successfully")

Note that this will still give an error if the stack is empty and you tried to pop something.

Sign up to request clarification or add additional context in comments.

4 Comments

I did that but I still can't exit the loop, how can I resolve that?
Oh shoot I forgot something important. Check the edited answer.
The function still not exiting the loop, how to break the loop?
Could you share test data?
0

You are assigning the next node first and then printing the popped element. What you should really do is first print the value and then move to next node. Afterwards, you have a while that will take care if next node is empty.

Change your pop like this:

def pop(self):
    if self.top:
        curr_node = self.top
        while curr_node:
            print(curr_node.data, "is popped successfully")
            curr_node = curr_node.next
    else:
        print("Stack is empty !")

1 Comment

The function still not exiting the loop, how to break the loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.