棧一:用兩個棧實現佇列
阿新 • • 發佈:2018-11-16
/**
* 題目:用兩個棧實現佇列
* 描述:用兩個棧來實現一個佇列,完成佇列的Push和Pop操作。 佇列中的元素為int型別。
* 解決方案:方法一:一個作為儲存用,一個作為彈出用
* */
public class One { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); public void push(int node) { stack1.push(node); }public int pop() { if (stack1.isEmpty() && stack2.isEmpty()) { throw new RuntimeException("Empty"); }else { if(stack2.isEmpty()) { while(!stack1.isEmpty()) { stack2.push(stack1.pop()); } } }return stack2.pop(); } }