Talk is cheap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-08-09 10:42:22
# @Author : Simon (simon.xie@codewalker.meg)
# @Link : http://www.codewalker.me
# @Version : 1.0.0


class Element(object):
def __init__(self, value):
self.value = value
self.next = None


class LinkedList(object):
def __init__(self, head=None):
self.head = head

def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element

def insert_first(self, new_element):
"Insert new element as the head of the LinkedList"
current = self.head
self.head = new_element
new_element.next = current

def delete_first(self):
"Delete the first (head) element in the LinkedList as return it"
current = self.head.next
self.head = current


class Stack(object):
def __init__(self, top=None):
self.ll = LinkedList(top)

def push(self, new_element):
"Push (add) a new element onto the top of the stack"
self.ll.insert_first(new_element)

def pop(self):
"Pop (remove) the first element off the top of the stack and return it"
if self.ll.head == None:
return None
current = self.ll.head
self.ll.delete_first()
return current


def main():
# Test cases
# Set up some Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)

# Start setting up a Stack
stack = Stack(e1)

# Test stack functionality
stack.push(e2)
stack.push(e3)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop())
stack.push(e4)
print(stack.pop().value)


if __name__ == "__main__":
main()