leetcode stack 232. Implement Queue using Stacks

法一:使用两个栈模拟队列。

class Queue {
private:
    stack<int> q_input;
    stack<int> q_output;
public:
    // Push element x to the back of queue.
    void push(int x) {
        q_input.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        while(!q_input.empty())
        {
            int top_tmp = q_input.top();
            q_input.pop();
            q_output.push(top_tmp);
        }

        if(!q_output.empty())
            q_output.pop();
        while(!q_output.empty())
        {
            int top_tmp = q_output.top();
            q_output.pop();
            q_input.push(top_tmp);
        }
    }

    // Get the front element.
    int peek(void) {
        while(!q_input.empty())
        {
            int top_tmp = q_input.top();
            q_input.pop();
            q_output.push(top_tmp);
        }

        int result = 0;
        if(!q_output.empty())
            result = q_output.top();

        while(!q_output.empty())
        {
            int top_tmp = q_output.top();
            q_output.pop();
            q_input.push(top_tmp);
        }        

        return result;
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return q_input.empty();
    }
};

优美的写法:

class Queue {
    stack<int> input, output;
public:

    void push(int x) {
        input.push(x);
    }

    void pop(void) {
        peek();
        output.pop();
    }

    int peek(void) {
        if (output.empty())
            while (input.size())
                output.push(input.top()), input.pop();
        return output.top();
    }

    bool empty(void) {
        return input.empty() && output.empty();
    }
};

法二:高效使用stack,使用递归来做

class Queue {
public:
    stack<int> s;

    // Push element x to the back of queue.
    void push(int x) {
        pushHelper(x);
    }

    void pushHelper(int x){
        if(s.size()==0){
            s.push(x);
            return;
        }
        int data;
        data = s.top();
        s.pop();
        pushHelper(x);
        s.push(data);
        return;
    }

    // Removes the element from in front of queue.
    void pop(void) {
        s.pop();
    }

    // Get the front element.
    int peek(void) {
        return s.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return (s.size()==0);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值