232.用栈实现队列
用栈实现队列的输出需要借助两个栈,先将队列的数据放进栈1,然后将栈1中的数据放进栈2中,只要栈2里面的数据非空,就将栈1里面的元素往里面放。
class MyQueue {
public Stack<Integer> stackIn;
public Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.pop();
}
public int peek() {
int result = this.pop();// 和pop里面可以进行代码复用
stackOut.push(result);// pop出来了,再放进去
return result;
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.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用队列实现栈
用队列实现栈可以借助两个单向队列,有一个简便的方法,借助双向队列,将栈里面的数据先放进队列里,然后在队列里面的元素,由于想弹出的元素在队列的最里面,此时将最里面元素之前的元素都弹出,再放到该队列的末尾即可。
class MyStack {
public Deque<Integer> q1;//双端队列
public MyStack() {
q1=new ArrayDeque<>();
}
public void push(int x) {
q1.addLast(x);
}
public int pop() {
int size=q1.size();
size--;
while(size>0){
q1.addLast(q1.pollFirst());
size--;
}
return q1.pollFirst();
}
public int top() {
return q1.peekLast();
}
public boolean empty() {
return q1.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();
*/