** * 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:感谢左程云老师的 程序员代码面试指南