用棧實現佇列的先進先出結構
阿新 • • 發佈:2019-01-03
** * By returnZhang * 兩個佇列組成棧 * stackIn 壓入資料 * stackOut 反轉資料 */ public class StackToList { Stack<Integer> stackIn;//資料棧 Stack<Integer> stackOut;//反轉棧 public StackToList(){ stackIn=new Stack<>(); stackOut=new Stack<>(); } //壓入資料 public void add(Integer num){ stackIn.push(num); } //彈出資料,反轉棧有資料則直接彈出資料,沒有則把壓入資料的棧反轉 public Integer poll() throws Exception { //如果反轉棧有資料則直接彈出 if(!stackOut.isEmpty()){ return stackOut.pop(); }else{ //反轉棧沒有資料則把資料站資料依次壓入反轉棧 //空檢測 if(stackIn.isEmpty()){ throw new Exception("there is nothing to do"); } // while (!stackIn.isEmpty()){ stackOut.push(stackIn.pop()); } } return stackOut.pop(); } }
ps:感謝左程雲老師的 程式設計師程式碼面試指南