232.用栈实现队列 225. 用队列实现栈
原创
©著作权归作者所有:来自51CTO博客作者龙崎流河的原创作品,请联系作者获取转载授权,否则将追究法律责任
232.用栈实现队列


栈实现队列,只有出队时比较复杂。
比如连续入栈1,2,3,4

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

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

到这里如果要是出队的话,直接出栈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();
*/

225. 用队列实现栈


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


入栈2



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