225. Implement Stack using Queues (栈实现队列)
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
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
1 class MyStack { 2 private: queue<int> q; 3 public: 4 /** Initialize your data structure here. */ 5 MyStack() { 6 7 } 8 9 /** Push element x onto stack. */ 10 void push(int x) { 11 int n = q.size(); 12 q.push(x); 13 for(int i = 0;i < n ;++i) { 14 q.push(q.front()); 15 q.pop(); 16 } 17 } 18 19 /** Removes the element on top of the stack and returns that element. */ 20 int pop() { 21 int v = q.front(); 22 q.pop(); 23 return v; 24 } 25 26 /** Get the top element. */ 27 int top() { 28 return q.front(); 29 } 30 31 /** Returns whether the stack is empty. */ 32 bool empty() { 33 return q.empty(); 34 } 35 }; 36 37 /** 38 * Your MyStack object will be instantiated and called as such: 39 * MyStack* obj = new MyStack(); 40 * obj->push(x); 41 * int param_2 = obj->pop(); 42 * int param_3 = obj->top(); 43 * bool param_4 = obj->empty(); 44 */