做商务网站公司,德清建设银行网站,wordpress密码_,现在做网站还用dw做模板了吗题目描述 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作#xff08;push、pop、peek、empty#xff09;#xff1a;
实现 MyQueue 类#xff1a; void push(int x) 将元素 x 推到队列的末尾 int pop() 从队列的开头移除并返回元素 int peek() 返…题目描述 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作push、pop、peek、empty
实现 MyQueue 类 void push(int x) 将元素 x 推到队列的末尾 int pop() 从队列的开头移除并返回元素 int peek() 返回队列开头的元素 boolean empty() 如果队列为空返回 true 否则返回 false
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
示例 1
输入 [“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”] [[], [1], [2], [], [], []] 输出 [null, null, null, 1, 1, false]
解释 MyQueue myQueue new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
解题思想 在pop的时候必须判断out栈是否为空如果为空则讲in栈中的元素全部放到out栈中否则输出out的栈顶元素。
代码
class MyQueue {
public:stackint stack_in;stackint stack_out;MyQueue() {}void push(int x) {stack_in.push(x);}int pop() {if (stack_out.empty()) {while (!stack_in.empty()) {stack_out.push(stack_in.top());stack_in.pop();}}int result stack_out.top();stack_out.pop();return result;}int peek() {int result this-pop();stack_out.push(result);return result;}bool empty() {return stack_in.empty() stack_out.empty();}
};