Implement Queue by Two Stacks

来源:互联网 发布:g3开票软件 编辑:程序博客网 时间:2024/06/04 17:59

 Implement Queue by Two Stacks

30:00

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element)pop() andtop() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.


看代码实现

/** * Created by jason on 2016/3/3. */class Queue {    private Stack<Integer> stack1;    private Stack<Integer> stack2;    public Queue() {        //do something        stack1 = new Stack<Integer>();        stack2 = new Stack<Integer>();    }    public void stack1Tostack2() {        while (!stack1.empty()) {            stack2.push(stack1.peek());            stack1.pop();        }    }    public void push(int element) {        stack1.push(element);    }    public int pop() {        if (stack2.empty()) {            this.stack1Tostack2();        }        return stack2.pop();    }    public int top() {        if (stack2.empty()) {            this.stack1Tostack2();        }        return stack2.peek();    }}



0 0