232.用栈实现队列

232.用栈实现队列 225. 用队列实现栈_java

232.用栈实现队列 225. 用队列实现栈_入栈_02


栈实现队列,只有出队时比较复杂。

比如连续入栈1,2,3,4

232.用栈实现队列 225. 用队列实现栈_出队_03


如果想要出队,那么需要出队1,所以将stack1的所有元素出栈入栈到stack2中

232.用栈实现队列 225. 用队列实现栈_c++_04


出栈stack2即可,如果再入栈5,继续入栈stack1

232.用栈实现队列 225. 用队列实现栈_入栈_05


到这里如果要是出队的话,直接出栈stack2即可,直到stack2为空时,再将stack1中的元素入栈到stack2中。

入栈一直入栈stack1。

这样就实现了两个栈完成队列操作。

class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}

public void push(int x) {
stack1.push(x);
}

public int pop() {
if(!stack2.isEmpty()){
return stack2.pop();
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();

}

public int peek() {
if(!stack2.isEmpty()){
return stack2.peek();
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.peek();
}

public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
}

/**
* 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();
*/

232.用栈实现队列 225. 用队列实现栈_c++_06

225. 用队列实现栈

232.用栈实现队列 225. 用队列实现栈_c++_07


232.用栈实现队列 225. 用队列实现栈_算法_08


与上题相反,队列实现栈,复杂在入栈操作。

队列1时辅助队

入栈1

232.用栈实现队列 225. 用队列实现栈_出队_09


232.用栈实现队列 225. 用队列实现栈_java_10


入栈2

232.用栈实现队列 225. 用队列实现栈_java_11


232.用栈实现队列 225. 用队列实现栈_java_12


232.用栈实现队列 225. 用队列实现栈_出队_13

class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}

public void push(int x) {
queue1.add(x);
while(!queue2.isEmpty()) queue1.add(queue2.poll());
//交换a,b队列
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
}

public int pop() {
return queue2.poll();
}

public int top() {
return queue2.peek();
}


public boolean empty() {
return queue2.isEmpty();
}
}

/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/

232.用栈实现队列 225. 用队列实现栈_入栈_14