题目:用两个栈实现队列,能够支持级别的操作(add poll peek)
思路:用一个栈存数据,另一个负责取数据,当取数据的栈空的时候,就把存数据的那个栈的数据全部取过来就行了,当两个栈都为空,则队列为空
import java.util.Stack;
public class StackToQueue {
public Stack<Integer> inStack = new Stack<Integer>();
public Stack<Integer> outStack = new Stack<Integer>();
public void add(int e){
inStack.push(e);
}
public int poll(){
if(inStack.isEmpty()&&outStack.isEmpty())
throw new RuntimeException("stack is empty ");
else if(outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.pop();
}
public int peek(){
if(inStack.isEmpty()&&outStack.isEmpty())
throw new RuntimeException("stack is empty ");
else if(outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
}