思路:两个栈,stackPop用来出队,stackPush用来入队;
入队时直接将元素压入stackPush里就好了;
出队时先判断stackPop里是否有元素,1)如果有,直接调用stackPop里的pop函数即可,2)如果stackpPop里没有元素,则将stackPush中元素(最后一个元素除外)依次pop出来并push进stackPop里,最后将stackPush中的留下的一个元素pop出来即可。代码如下:
/**
* @author robin
* @date 2019年6月14日
* @time 下午1:46:03
*/
package com.test1;
import java.util.Stack;
public class TwoStackQueue {
Stack<Integer> stackPop;
Stack<Integer> stackPush;
public TwoStackQueue() {
// TODO Auto-generated constructor stub
stackPop=new Stack<Integer>();
stackPush=new Stack<Integer>();
}
public void add(int toPush) {
stackPush.push(toPush);
}
public int poll() {
if (stackPop.isEmpty()&&stackPush.isEmpty()) {
throw new RuntimeException("Queue is empty!");
}
if (!stackPop.isEmpty()) {
return stackPop.pop();
}else {
while (stackPush.size()>1) {
stackPop.push(stackPush.pop());
}
return stackPush.pop();
}
}
public int size() {
return stackPop.size()+stackPush.size();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TwoStackQueue twoStackQueue=new TwoStackQueue();
twoStackQueue.add(0);
System.out.println(twoStackQueue.poll());
twoStackQueue.add(1);
twoStackQueue.add(2);
twoStackQueue.add(3);
twoStackQueue.add(4);
twoStackQueue.add(5);
while (twoStackQueue.size()>0) {
System.out.println(twoStackQueue.poll());
}
}
}