225 队列实现stack
解决方法简单粗暴,把队列前面的都取出来再加入队尾,让之前的队尾元素排到队头,这样就可以取出了:
import queue class MyStack: def __init__(self): self.q = queue.Queue() self.top_element = 0 def push(self, x: int) -> None: self.q.put(x) self.top_element = x def pop(self) -> int: sz = self.q.qsize() while sz > 2: self.q.put(self.q.get()) sz -= 1 self.top_element = self.q.get() self.q.put(self.top_element) return self.q.get() def top(self) -> int: return self.top_element def empty(self) -> bool: return self.q.qsize() == 0