有苦有乐的算法 --- 使用栈结构实现队列结构
题目
栈实现队列
解析
两个栈,stack1,stack2

假如一组元素为[1,2,3,4,5],
先依次入stack1

在将stack1的所有数据出栈,在入stack2
注:stack1里的的数据一定要一起出栈;stack2中有数据stack1里的的数据不能出栈
stack2出栈即可实现队列操作
代码
public static class TwoStacksQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStacksQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
// push栈向pop栈倒入数据
private void pushToPop() {
if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
}
public void add(int pushInt) {
stackPush.push(pushInt);
pushToPop();
}
public int poll() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.pop();
}
public int peek() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.peek();
}
}
浙公网安备 33010602011771号