LeetCode学习之-232. 利用堆栈实现队列(Implement Queue using Stacks)

来源:互联网 发布:售票软件 编辑:程序博客网 时间:2024/06/05 14:33

1.算法

[1]

2.代码

[2]

"""Author: Tianze TangDate: 2017-07-17Email:454779758@qq.comFunction: Use two stack to realize queue's function.Explain:Modified Log:"""class MyQueue():    def __init__(self):        self.inStack,self.outStack = [1,2,3,4,5,6],[]    # move all elements of the "inStack" to     # the "outStack" is empty    def move(self):        """        :rtype nothing        """        if not self.outStack:            while self.inStack:                self.outStack.append(self.inStack.pop())    def top(self):        """        :rtype: int        """        self.move()        return self.outStack[-1]    def empty(self):        """        :rtype: bool        """        return (not self.inStack) and (not self.outStack)    def push(self,x):        """        :type x: int        :rtype: nothing        """        self.inStack.append(x)    def pop(self):        """        :rtype: nothing        """        self.move()        self.outStack.pop()""" * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * bool param_4 = obj.empty(); *"""t=MyQueue()# push "7" into the queue's tailt.push(7)print(t.inStack,t.outStack)# pop "1" out the queue's headt.pop()print(t.inStack,t.outStack)# find the top of the queueTop = t.top()print(Top)# judge the queue empty or notTest =t.empty()print(Test)

3.输出

[1, 2, 3, 4, 5, 6, 7] []
[] [7, 6, 5, 4, 3, 2]
2
False

4.参考资料

[1] 《算法导论》第3版 :第10章 基本数据结构 10.1栈和列队
[2] Share my python solution (32ms)

阅读全文
0 0