This is my Stack implementation.
class Stack:
def __init__(self):
self.head = None
self.size = 0
def push(self, item):
node
Because you can have more than one iterator on the same stack, __iter__
has to return a iterator-object, that iterates the stack:
class Stack:
def __init__(self):
self.head = None
self.size = 0
def push(self, item):
node = Node(item)
if self.head:
node.next = self.head
self.head = node
self.size += 1
def pop(self):
if self.size == 0:
raise ValueError('Popping off an empty stack!')
item = self.head.val
self.head = self.head.next
return item
def peek(self):
if self.size == 0:
raise ValueError('Peeking into an empty stack!')
return self.head.val
def __iter__(self):
return StackIterator(self.head)
class StackIterator:
def __init__(self, head):
self.head = head
def __iter__(self):
return self
def __next__(self):
if not self.head:
raise StopIteration()
item = self.head.val
self.head = self.head.next
return item