问题描述:
如何仅用栈实现队列?
思路:用两个栈实现队列
在队列入队的时候元素进入stackPush栈,元素出队的时候,将stackPush栈里面的元素倒入stackPop栈中,然后依次从stackPop栈里面弹出,在倒数据时有两个条件:1.如果要倒数据就一次性倒完,2.如果help栈中有元素则不能倒,只要满足该条件,就可以倒数据,并且倒数据可以发生在任何时刻
package code001_code010;
import java.util.Stack;
public class Code_002_StackToQueue {
public static class StackToQueue{
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public StackToQueue() {
stackPush = new Stack<>();
stackPop = new Stack<>();
}
public void enqueue(int obj) {
stackPush.push(obj);
}
public int dequeue() {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new RuntimeException("Dequeue failed, Queue is null");
} else if (stackPop.isEmpty()) {
while(!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek() {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new RuntimeException("Dequeue failed, Queue is null");
} else if (stackPop.isEmpty()) {
while(stackPush.size() > 0) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}
}