"A book to train programming skills to fight in the world" Python code answer example --3.1 Three stacks
python
class FixedMultiStack:
def __init__(self, stackSize):
numberOfStacks = 3
self.stackCapacity = stackSize
self.values = [0] * (stackSize * numberOfStacks)
self.sizes = [0] * numberOfStacks
def indexOfTop(self,stackNum):
offset = stackNum * self.stackCapacity
size = self.sizes[stackNum]
return offset + size - 1
def isFull(self,stackNum):
return self.sizes[stackNum] == self.stackCapacity
def push(self,stackNum,value):
if self.isFull(stackNum):
raise Exception("FullStackException")
self.sizes[stackNum] = self.sizes[stackNum] + 1
self.values[self.indexOfTop(stackNum)] = value
def isEmpty(self,stackNum):
return self.sizes[stackNum] == 0
def pop(self,stackNum):
if self.isEmpty(stackNum):
raise Exception("EmptyStackException")
topIndex = self.indexOfTop(stackNum)
value = self.values[topIndex]
self.values[topIndex] = 0
self.sizes[stackNum] = self.sizes[stackNum] - 1
return value
def peek(self,stackNum):
if self.isEmpty(stackNum):
raise Exception("EmptyStackException")
return self.values[self.indexOfTop(stackNum)]
FMS = FixedMultiStack(5)
print(FMS.values)
FMS.push(0,1)
FMS.push(1,6)
FMS.push(2,11)
print(FMS.values)
FMS.push(0,2)
FMS.push(0,3)
FMS.push(0,4)
FMS.push(0,5)
print(FMS.values)
FMS.pop(0)
FMS.pop(1)
print(FMS.values)
print(FMS.peek(0))
print(FMS.peek(2))