在面试中被问到这类题目,由于当时并没有太留心,栽了两次,实在不应该。总结到博客,方便后面翻出来时时复习。
用队列实现栈
这里的思想是用两个队列实现一个栈,交替进行存储和弹出数据,很好的图解详见:点击打开链接。
关于这里队列的实现,可以用实现了Queue接口的ArrayDeque或者LinkedList,改一下import的包就好了。
import java.util.ArrayDeque;
import java.util.Queue;
public class TwoQueueStack {
Queue<Integer> queue1 = new ArrayDeque<Integer>(); //两个队列实现一个栈
Queue<Integer> queue2 = new ArrayDeque<Integer>();
public void push(Integer element) {
if(queue1.isEmpty() && queue2.isEmpty()) { //两个队列均空,优先在第一个队列压入数据
queue1.add(element);
}
else if(queue1.isEmpty()) {
queue2.add(element);
}
else {
queue1.add(element);
}
}
public Integer pop() {
if(queue1.isEmpty() && queue2.isEmpty()) { //两个队列均空,弹出数据报错
try {
throw new Exception("Stack is Empty!");
}catch(Exception e) {
e.printStackTrace();
}
}
else if(queue1.isEmpty()) {
while(queue2.size() > 1) {
queue1.add(queue2.poll());
}
return queue2.poll();
}
else {
while(queue1.size() > 1) {
queue2.add(queue1.poll());
}
return queue1.poll();
}
return (Integer)null; //对于两个队列均空情况返回null
}
public static void main(String[] args) {
TwoQueueStack queueStack = new TwoQueueStack();
queueStack.push(1);
queueStack.push(2);
queueStack.push(3);
queueStack.push(4);
System.out.println(queueStack.pop());
System.out.println(queueStack.pop());
queueStack.push(5);
System.out.println(queueStack.pop());
}
}
用栈实现队列
这里的思想也是用两个栈实现一个队列,和上一种情况有点区别,第一个栈只负责存储数据,另一个栈只用于弹出数据。
import java.util.Stack;
public class TwoStackQueue {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void add(Integer element) {
stack1.push(element);
}
public Integer poll() {
if(stack2.isEmpty()) { //判断第二个栈为空,第一个栈中元素弹出到第二个栈
while(stack1.size() > 0) {
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()) { //判断第二个栈仍为空,报错
try {
throw new Exception("Queue is Empty");
}catch(Exception e) {
e.printStackTrace();
}
}
return stack2.pop();
}
public static void main(String[] args) {
TwoStackQueue stackQueue = new TwoStackQueue();
stackQueue.add(1);
stackQueue.add(2);
stackQueue.add(3);
System.out.println(stackQueue.poll());
System.out.println(stackQueue.poll());
stackQueue.add(5);
System.out.println(stackQueue.poll());
}