LintCode-40. 用栈实现队列

题目

描述

正如标题所述,你需要使用两个栈来实现队列的一些操作。

队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。

pop和top方法都应该返回第一个元素的值。

样例

例1:

输入:
    push(1)
    pop()    
    push(2)
    push(3)
    top()    
    pop()     
输出:
    1
    2
    2

例2:

输入:
    push(1)
    push(2)
    push(2)
    push(3)
    push(4)
    push(5)
    push(6)
    push(7)
    push(1)
输出:
[]

解答

思路

两个栈,一个负责入,一个负责出。每次入/出,都是吧一个栈的数据倒到另外一个栈里面在入/出。

代码

public class MyQueue {
    
    // 作为入队序列
    private Stack s1 = new Stack();
    // 作为出队序列
    private Stack s2 = new Stack();

    public MyQueue() {
        // do intialization if necessary
    }

    /*
     * @param element: An integer
     * @return: nothing
     */
    public void push(int element) {
        // write your code here
        while(!s2.empty()){
            s1.push(s2.pop());
        }
        s1.push(element);
    }

    /*
     * @return: An integer
     */
    public int pop() {
        // write your code here
        while(!s1.empty()){
            s2.push(s1.pop());
        }
        return s2.pop();
    }

    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
        while(!s1.empty()){
            s2.push(s1.pop());
        }
        return s2.peek();
    }
}

你可能感兴趣的:(LintCode-40. 用栈实现队列)