Skip to content

Instantly share code, notes, and snippets.

@bulv1ne
Last active August 29, 2015 14:00
Show Gist options
  • Save bulv1ne/11281765 to your computer and use it in GitHub Desktop.
Save bulv1ne/11281765 to your computer and use it in GitHub Desktop.
from collections import namedtuple
Node = namedtuple('Node', 'value next')
class Stack(object):
def __init__(self):
self.top = None
def push(self, value):
n = Node(value, self.top)
self.top = n
def pop(self):
if not self.top:
return None
try:
return self.top.value
finally:
self.top = self.top.next
def itervalues(self):
top = self.top
while top:
yield top.value
top = top.next
def values(self):
return list(self.itervalues())
if __name__ == '__main__':
stack = Stack()
assert stack.pop() == None
stack.push('foo')
assert stack.pop() == 'foo'
assert stack.pop() == None
stack.push('bar')
stack.push('baz')
stack.push('foobar')
assert stack.values() == ['foobar', 'baz', 'bar']
assert stack.pop() == 'foobar'
assert stack.pop() == 'baz'
assert stack.pop() == 'bar'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment