这题其实很容易,就讲个思路吧。先把元素入栈一个栈1,然后,再把这个栈1中所有元素出栈到另一个栈2,此时,栈1的栈底元素就到栈2的栈顶了,再对栈2出栈就是先进先出了。
不过。此题需要注意的一点就是,如果此时再进行入队列操作,只能对栈1入栈,并且,如果栈2不为空的话,是不能将栈1中元素入栈栈2的,不然就会出错,就不是先进先出了,这个细节需要注意一下。这题很简单,就是简单出栈入栈而已,注意一下这个细节就行了。
public static class TwoStackQueue{
private Stack<Integer> s1=new Stack();
private Stack<Integer> s2=new Stack();
public void push(int obj){
s1.push(obj);
}
public Integer pop(){
if(s1.empty()&&s2.empty()){
throw new ArrayIndexOutOfBoundsException("队列为空");
}else if(s2.empty()){
while (!s1.empty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
public Integer peek(){
if(s1.empty()&&s2.empty()){
throw new ArrayIndexOutOfBoundsException("队列为空");
}else if(s2.empty()){
while (!s1.empty()){
s2.push(s1.pop());
}
}
return s2.peek();
}
}