forked from alvinctk/google-tech-dev-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_array.py
More file actions
82 lines (73 loc) · 2 KB
/
stack_array.py
File metadata and controls
82 lines (73 loc) · 2 KB
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
81
82
"""
List(or array) implementation of a stack
Space used must be linear in the number of items in a stack
Stack() -> creates a new Stack object
.is_empty()
len() -> number of elements in stack
.push(item) -> push item into Stack
.pop() -> Remove and return the most recent item in the stack
"""
class Stack:
"""
List(or array) implementation of a stack
"""
def __init__(self):
"""
Initialize the stack
"""
self.top = []
def __len__(self):
"""
Returns the len of a stack
For example:
s = Stack()
len(s) gives 0
"""
return len(self.top)
def __str__(self):
"""
Returns the string representation of a stack
"""
this_str = "Stack: Top of stack ["
n = len(self.top)
for i, current in enumerate(self.top):
this_str += str(current)
if i + 1 < n:
this_str += " -> "
this_str += "] Bottom of stack; length = {}".format(len(self.top))
return this_str
def is_empty(self):
"""
Returns True if the stack has no items and empty; Otherwise, False
"""
return len(self.top) == 0
def push(self, item):
"""
Add item into the stack following first in last out (LIFO)
That is, the most recently added element is at the top of the stack.
Returns None
"""
# Reassign the link to top of the stack and update the
self.top = [item] + self.top
def pop(self):
"""
Remove the top item in the stack
Returns the top item of the stack
"""
popped_node = self.top[0]
self.top = self.top[1:]
return popped_node
if __name__ == "__main__":
s = Stack()
# Test stack
for x in [1, 2, 3, 4 ,5]:
s.push(x)
print(s)
x = Stack()
while not s.is_empty():
x.push(s.pop())
#print("x", x)
#print("s", s)
s.push(None)
print("x", x)
print("s", s)