栈实现队列和队列实现栈的本质都是在push功能上进行修改,从而使出队和出栈方式相同,所以重点在push()函数
232用栈实现队列
使用两个栈,先将1栈中的内容遍历push到2栈,再将元素x push进去,然后再将栈2元素遍历到1栈,则1栈的出栈顺序就跟队列相同。
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>(); // 负责进栈
stackOut = new Stack<>(); // 负责出栈
}
public void push(int x) {
while (!stackOut.empty()){
stackIn.push(stackOut.pop());
}
stackIn.push(x);
while (!stackIn.empty()){
stackOut.push(stackIn.pop());
}
}
public int pop() {
return stackOut.pop();
}
public int peek() {
return stackOut.peek();
}
public boolean empty() {
return stackOut.empty();
}
}
225用队列实现栈
先将x 存入队列2,再将队列1中的元素存入队列2,最后再将队列2中的元素存入队列1,则队列1的出队顺序和出栈一致。
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue2.offer(x);
queue2.addAll(queue1);
queue1.clear();
queue1.addAll(queue2);
queue2.clear();
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
if (queue1.size()==0){
return true;
}else {
return false;
}
}
}
收获
栈与队列的初始化方式不同
queue = new LinkedList<>();
stack = new Stack<>();