-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.py
70 lines (56 loc) · 1.44 KB
/
stack.py
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
from util import LinkList
class Stack(object):
'''
A Last In, First Out (LIFO) data structure.
ref: http://alrightchiu.github.io/SecondRound/stack-introjian-jie.html
'''
def __init__(self):
self.linklist = LinkList()
def pushFront(self, data):
self.linklist.pushFront(data)
def top(self):
'''
just get the top element
'''
if self.isEmpty():
return None
return self.linklist.firstNode.data
def pop(self):
'''
remove and return the top element
'''
if self.isEmpty():
return None
data = self.linklist.firstNode.data
self.linklist.delete(data)
return data
def size(self):
'''
return the size of Stack
'''
return self.linklist.size()
def isEmpty(self):
'''
check if Stack is empty
'''
return not bool(self.linklist.size)
def printStack(self):
self.linklist.printAll()
if __name__ == "__main__":
stack = Stack()
stack.pushFront(123)
stack.pushFront(456)
stack.pushFront(789)
stack.printStack()
pop = stack.pop()
print(f"pop out: {pop}")
stack.printStack()
pop = stack.pop()
print(f"pop out: {pop}")
stack.printStack()
pop = stack.pop()
print(f"pop out: {pop}")
stack.printStack()
pop = stack.pop()
print(f"pop out: {pop}")
stack.printStack()