package java_study.JianZhiOffer;
import java.util.Stack;
/**
* Created by ethan on 2015/6/22.
*/
public class No7Queue {
public Stack<Integer> stackInput;
public Stack<Integer> stackOutput;
public No7Queue(){
stackInput = new Stack<Integer>();
stackOutput = new Stack<Integer>();
}
public void push(int x){
stackInput.push(x);
}
public boolean isEmpty() throws Exception{
if (stackInput==null || stackOutput==null)
throw new NullPointerException();
if (stackInput.isEmpty()&&stackOutput.isEmpty())
return true;
else
return false;
}
public int pop() throws Exception{
if (this.isEmpty()) throw new Exception("this Queue is empty");
if (stackOutput.isEmpty()){
while (!stackInput.isEmpty()){
stackOutput.push(stackInput.pop());
}
}
return stackOutput.pop();
}
public int top() throws Exception{
if (this.isEmpty()) throw new Exception("this Queue is empty");
if (stackOutput.isEmpty()){
while (!stackInput.isEmpty()){
stackOutput.push(stackInput.pop());
}
}
return stackOutput.peek();
}
}
兩個棧實現一個隊列
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.