import java.util.Stack;
/**
* 问题:用两个Stack来实现一个Queue;
* 方法:栈的特点是先进后出;而队列的特点是先进先出;
* 用两个栈正好能把顺序调过来;
* 一个栈,作为压入栈,在压入数据时,只往这个栈里压入,记作:stackPush;
* 一个栈 ,作为弹出栈,在弹出数据时,只从这个栈里弹出,记作:stackPop;
*
*/
public class TwoStackQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackQueue(){
this.stackPush = new Stack<Integer>();
this.stackPop = new Stack<Integer>();
}
//向队列中添加元素;
public void add(int pushInt) {
stackPush.push(pushInt);
}
//从队列中删除元素;
public int poll() {
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 int peek() {
if(stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
} else if(stackPop.empty()) {
while(!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
//测试程序
public static void main(String[] args) {
TwoStackQueue tsq = new TwoStackQueue();
int[] a = {1, 2, 3, 4, 5, 6, 7};
for(int i: a){
tsq.add(i);
}
for(int j=0; j<a.length; j++) {
int num = tsq.peek();
tsq.poll();
System.out.println(num);
}
}
}