一:队列去实现一个栈
代码实现
public class QueueToStack {
private Queue<Integer> inQueue;//插入队列
private Queue<Integer> outQueue;//输出队列
public QueueToStack() {
inQueue = new LinkedList<>();
outQueue = new LinkedList<>();
}
public void push(int x) {
//直接插入空的队列当中
inQueue.offer(x);
while (!outQueue.isEmpty()) {
inQueue.offer(outQueue.poll());
}
Queue<Integer> tmp = inQueue;
inQueue = outQueue;
outQueue = tmp;
}
public int pop() {
if (empty()) {
return -1;
}
return outQueue.poll();
}
public int top() {
if (empty()) {
return -1;
}
return outQueue.peek();
}
public boolean empty() {
return outQueue.isEmpty();
}
}
二:用栈去实现队列
代码实现
public class StackToQueue {
private Stack<Integer> inStack;
private Stack<Integer> outStack;
public StackToQueue() {
inStack=new Stack<>();
outStack=new Stack<>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if(empty()){
return -1;
}
if(outStack.isEmpty()){
//出栈的元素没有
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.pop();
}
public int peek() {
if(empty()){
return -1;
}
if(outStack.isEmpty()){
//出栈的元素没有
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty()&& outStack.isEmpty();
}
}