-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_of_plates.py
70 lines (56 loc) · 1.46 KB
/
stack_of_plates.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
# 3.3: Stack of Plates
from stack import Node
# Runtime: O(1) - Space: O(1)
class StackInfo:
def __init__(self):
self.capacity = 3
self.size = 0
self.top = None
class SetOfStacks:
def __init__(self):
self.stacks = []
def print(self):
for idx, stack in enumerate(self.stacks):
print(
f"stack # {idx}: top: {stack.top.value} | stack size: {stack.size}"
)
def push(self, value):
new_top = Node(value)
info = self.stacks[-1] if self.stacks else StackInfo()
if info.size < info.capacity:
new_top.next = info.top
info.size += 1
info.top = new_top
else:
info = StackInfo()
info.size += 1
info.top = new_top
self.stacks.append(info)
if not self.stacks:
self.stacks.append(info)
def pop(self):
info = self.stacks[-1]
info.size -= 1
item = info.top
if info.top.next:
info.top = info.top.next
else:
self.stacks.pop()
return item
stack = SetOfStacks()
stack.push(5)
stack.push(3)
stack.push(2)
stack.push(6)
stack.push(1)
stack.print()
print("popped:", stack.pop().value)
stack.print()
print("popped:", stack.pop().value)
stack.print()
print("popped:", stack.pop().value)
stack.print()
print("popped:", stack.pop().value)
stack.print()
print("popped:", stack.pop().value)
stack.print()