Created
February 6, 2013 00:00
-
-
Save kolauren/4718928 to your computer and use it in GitHub Desktop.
Coding for Interviews: Stack 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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