题目描述
// 232. 用栈实现队列
// 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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 操作是合法的。
// 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一
// 个栈,只要是标准的栈操作即可。
//
// 进阶:
// 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总
// 时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。
题解
/**
* 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.peek();
* boolean param_4 = obj.empty();
*/
// 这题很像【剑指offer】09.用两个栈实现队列
// 用两个栈,已经提示很明显了。
// 我们定义一个栈stack1用来入队(入栈),定义另外一个栈stack2用来出队(出栈)
// 只要入队元素必须到stack1中,只要出队元素必须到stack2中。
// 如果要出队,由于栈是先进后出,那stack1中所有元素出栈,然后再
// 入栈到stack2中,此时stack2栈顶到栈底就是先进先出的顺序了。
// 如果之前实现了pop,元素都在stack2中,此时要push元素进去,那又反过来
// 把stack2的元素全部出栈再入栈到stack1中,再把元素push进stack1。
//
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:36.2 MB, 在所有 Java 提交中击败了67.77%的用户
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
this.stack1 = new Stack<>();
this.stack2 = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
if (stack1.isEmpty()) {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
if (!stack2.isEmpty())
return stack2.pop();
return -1;
}
/** Get the front element. */
public int peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
if (!stack2.isEmpty())
return stack2.peek();
return -1;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return (stack1.isEmpty() && stack2.isEmpty());
}
}