实现思路
用两个栈来实现一个队列结构,将第一个栈的所有被压入值,读出来再压入第二个栈,实现栈的逆序操作,从而模拟队列的先进先出操作。
代码实现
import java.util.Stack;
public class Code_StackAndQueueConvert {
public static class TwoStackQueue{
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public void push(Integer obj) {
stackPush.push(obj);
}
public Integer pop() {
if(stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty.");
}else if(stackPop.empty()) {
while(!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
}
public static void main(String[] args) {
TwoStackQueue queue = new TwoStackQueue();
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
}
}