-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy paththree-in-one.py
64 lines (55 loc) · 1.81 KB
/
three-in-one.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
"""
Describe how you could use a single array to implement three stacks.
"""
class FixedMultiStack:
def __init__(self,capacity):
self.capacity = capacity
self.arr = [None] * 3 * capacity
self.sizes = [0] * 3
def push(self, stackNum, data):
if self.sizes[stackNum] == self.capacity:
print("Stack is already Full")
else:
self.sizes[stackNum] += 1
self.arr[self.indexOfTop(stackNum)] = data
def pop(self, stackNum):
if self.sizes[stackNum] == 0:
return "Stack is empty"
topIndex = self.indexOfTop(stackNum)
data = self.arr[topIndex]
self.arr[topIndex] = None
self.sizes[stackNum] -= 1
return data
def indexOfTop(self, stackNum):
offset = stackNum * self.capacity
s = self.sizes[stackNum]
return offset + s - 1
class MultiStack:
def __init__(self, capacity):
self.capacity = capacity
self.arr = [None] * 3 * capacity
self.top = [-1] * 3
self.nextt = [i+1 for i in range(3*capacity)]
self.nextt[-1] = -1
self.free = 0
def isFull(self):
return self.free == -1
def isEmpty(self, stackNum):
return self.top[stackNum] == -1
def push(self, stackNum, data):
if self.isFull():
print("Stack is Full")
return
i = self.free
self.free = self.nextt[i]
self.nextt[i] = self.top[stackNum]
self.top[stackNum] = i
self.arr[i] = data
def pop(self, stackNum):
if self.isEmpty(stackNum):
return None
i = self.top[stackNum]
self.top[stackNum] = self.nextt[i]
self.nextt[i] = self.free
self.free = i
return self.arr[i]