Chapter 3 Stacks and Queues - 3.3

Problem 3.3: Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks, and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop() should return the same values as it would if there were just a single stack).
FOLLOW UP
Implement a function popAt(int index) which performs a pop operation on a specific sub-stack.


It is a quite easy one. However, the requirement of follow up question is not clear and we should discuss details with interviewers.
from stack import *
MAX_CAPACITY = 3
class SetOfStacks:
    def __init__(self):
        self.stacks = [stack()]
        self.last = 0
    def push(self, value):
        if self.stacks[self.last].size() >= MAX_CAPACITY:
            self.stacks.append(stack())
            self.last = self.last + 1
        self.stacks[self.last].push(value)
    def pop(self):
        if self.stacks[self.last].size() <= 0:
            if len(self.stacks) <= 1:
                return False
            del self.stacks[self.last]
            self.last = self.last - 1
        return self.stacks[self.last].pop()
    def popAt(self, index):
        if (index < 0) or (index > self.last):
            return False
        to_return = self.stacks[index].pop()
        if self.stacks[index].size() <= 0:
            del self.stacks[index]
            self.last = self.last - 1
        return to_return


# Test cases
if __name__ == "__main__":
    stacks_set = SetOfStacks()
    for i in range(0, 10):
        print "push", i
        stacks_set.push(i)
    for i in range(0, 3):
        print "pop", stacks_set.pop()
    for i in range(0, 5):
        print "push", i
        stacks_set.push(i)
    for i in range(0, 13):
        print "popAt(0)", stacks_set.popAt(0)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值