This is my Stack implementation.
class Stack:
def __init__(self):
self.head = None
self.size = 0
def push(self, item):
node
The problem is that you do not make a difference between the iterable Stack itself and the iterator that __iter__ should return. __next__ should be called on said iterator, not on the Stack itself.
I propose the following solution:
class StackIterator:
def __init__(self, stack):
self.head = stack.head
def __iter__(self):
return self
def __next__(self):
if not self.head:
raise StopIteration
current = self.head
self.head = self.head.next
return current.val
Get rid of __next__ in Stack and adjust __iter__ to:
def __iter__(self):
return StackIterator(self)
Demo:
>>> stack = Stack()
>>> stack.push(12)
>>> stack.push(13)
>>> stack.push(9)
>>>
>>> for x in stack:
... print(x)
...
9
13
12
>>> stack.peek()
9