栈和队列---由两个栈组成队列

来源:互联网 发布:js获取id的属性值 编辑:程序博客网 时间:2024/05/21 11:25

【题目】

  编写一个类,用两个栈实现队列,支持队列的基本操作(add, poll, peek)。

【基本思路】

  使用两个栈stackpush、stackpop,stackpush栈负责压入数据、stackpop栈负责将stackpush中的元素逆序,用于获取或者弹出栈顶元素。但是有一个规则:stackpop只有为空的时候才再次向stackpush栈索要元素,而且,必须一次拿走stackpush中当前的所有元素。

【代码实现】

#python3.5class TwoStackQueue:    stackPush = []    stackPop = []    def add(self, newNum):        self.stackPush.append(newNum)    def poll(self):        if not self.stackPush and not self.stackPop:            raise Exception("Queue is empty!")        elif not self.stackPop:            while self.stackPush:                self.stackPop.append(self.stackPush.pop())        return self.stackPop.pop()    def peek(self):        if not self.stackPush and not self.stackPop:            raise Exception("Queue is empty!")        elif not self.stackPop:            while self.stackPush:                self.stackPop.append(self.stackPush.pop())        return self.stackPop[-1]