Skip to content

Instantly share code, notes, and snippets.

@kolauren
Created February 6, 2013 00:00
Show Gist options
  • Select an option

  • Save kolauren/4718928 to your computer and use it in GitHub Desktop.

Select an option

Save kolauren/4718928 to your computer and use it in GitHub Desktop.
Coding for Interviews: Stack 2
# A simple stack, LIFO fo' lyfe
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class Stack:
top = None
# put at item at the front of the stack
def push(self, item):
node = Node(item, self.top)
self.top = node
# remove the first item and return it
def pop(self):
old_top = self.top
self.top = old_top.next
old_top.next = None
return old_top.item
# sneak a look at the first item, but don't remove it
def peek(self):
return self.top.item
def print_me(self):
curr = self.top
print "=== current stack ==="
while curr != None:
print curr.item
curr = curr.next
def main():
s = Stack()
s.push("a")
s.push("b")
s.push("c")
s.push("d")
s.print_me()
print s.pop()
print s.pop()
print s.peek()
s.print_me()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment