题目
编写一个类,用两个栈实现队列,支持队列的基本操作(add, poll, peek)
要求
无
思路
使用两个栈,栈A用于add,栈B用于poll和peek,add的时候,往栈A中push元素,poll时,如果栈B不是空,则弹出最顶元素,如果为空则将栈A的所有元素pop,然后push到栈B中。这样就可以实现队列的功能了。
代码
package com.github.zhanyongzhi.interview.algorithm.stacklist;
import java.util.Stack;
/**
* 用两个栈实现队列
* @author zhanyongzhi
*/
public class TwoStackQueue<T> {
private Stack<T> pushStack = new Stack<T>();
private Stack<T> popStack = new Stack<T>();
public T add(T item){
pushStack.push(item);
return item;
}
public T poll(){
if(popStack.empty()){
moveStack();
}
if(!popStack.empty())
return popStack.pop();
return null;
}
public T peek(){
if(popStack.empty()){
moveStack();
}
if(!popStack.empty())
return popStack.peek();
return null;
}
private void moveStack(){
int count = pushStack.size();
for(int i=0; i<count; i++){
T item = pushStack.pop();
popStack.push(item);
}
}
}