題目
編寫一個類宣渗,用兩個棧實(shí)現(xiàn)隊(duì)列抖所,支持隊(duì)列的基本操作(add, poll, peek)
要求
無
思路
使用兩個棧,棧A用于add痕囱,棧B用于poll和peek田轧,add的時候,往棧A中push元素鞍恢,poll時傻粘,如果棧B不是空,則彈出最頂元素有序,如果為空則將棧A的所有元素pop抹腿,然后push到棧B中。這樣就可以實(shí)現(xiàn)隊(duì)列的功能了旭寿。
代碼
package com.github.zhanyongzhi.interview.algorithm.stacklist;
import java.util.Stack;
/**
* 用兩個棧實(shí)現(xiàn)隊(duì)列
* @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);
}
}
}