用队列实现栈
使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
使用两个队列
使用put()将元素添加到序列尾端,get()从队列尾部移除元素
from queue import Queue
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue_push = Queue()
self.queue_pop = Queue()
def push(self, x):
"""
Push element x onto stack.
"""
self.queue_push.put(x)
self.top_ele = x
def pop(self):
"""
Removes the element on top of the stack and returns that element.
"""
while (self.queue_push.qsize() > 1):
self.top_ele = self.queue_push.get()
self.queue_pop.put(self.top_ele)
res = self.queue_push.get()
self.queue_pop, self.queue_push = self.queue_push, self.queue_pop
return res
def top(self):
"""
Get the top element.
"""
return self.top_ele
def empty(self):
"""
Returns whether the stack is empty.
"""
#return self.queue_push.empty() and self.queue_pop.empty()
return self.in_que.qsize() + self.out_que.qsize() == 0
#have a try
stack = MyStack()
stack.push(-2)
stack.push(0)
stack.push(-3)
stack.push(5)
stack.push(-4)
print('栈中所有元素:',stack)
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.pop()
print('栈顶元素:',stack.top())
stack.empty()
print('栈顶元素:',stack.empty())
执行用时 :28 ms, 在所有 Python3 提交中击败了88.13%的用户