一、用两个栈实现队列:
class CQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
public CQueue() {
s1 = new Stack();
s2 = new Stack();
}
//入队列,都进入栈S1
public void appendTail(int value) {
s1.push(value);
}
//出队列,把S1都推入S2,再取出第一个
public int deleteHead() {
if (s2.isEmpty()){
while(!s1.isEmpty()) {
s2.push(s1.pop());
}
}
return s2.isEmpty() ? -1 : s2.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
二、用两个队列实现栈
import java.io.IOException;
import java.util.*;
/**
两个队列形成栈
*/
class MyStack {
Queue<Integer> a;
Queue<Integer> b;
/** Initialize your data structure here. */
public MyStack() {
a = new LinkedList<>();
b = new LinkedList<>();
}
//保证一个队列为空,插入空队列再将另一个队列中数据插入此队列
public void push(int x) {
a.offer(x);
while(!b.isEmpty()){
a.offer(b.poll());
}
Queue temp = a;
a = b;
b = temp;
}
//出栈,即将存有数据的非空队列输出一个数据
public int pop() {
return b.poll();
}
//获取栈顶元素,即获取存有数据的队列的队首数据且不删除
public int top() {
return b.peek();
}
//查看栈是否为空
public boolean empty() {
return b.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();
*/