题解 | #用两个栈实现队列#

用两个栈实现队列

http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

基于c++实现:

官方给的:

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        int temp;
        if(!stack2.empty()){
            temp = stack2.top();
            stack2.pop();
        }else{
            while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
            }
            temp = stack2.top(); 
            stack2.pop();
        }
        return temp;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

自己写的,还是差一点呦!

class Solution
{
public:
    void push(int node) {
        while(!stack2.empty()){
            stack1.push(stack2.top());
            stack2.pop();
            }
        stack1.push(node);
    }

    int pop() {
        int temp;
        while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
            }
        temp = stack2.top();
        stack2.pop();
        return temp;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
全部评论

相关推荐

08-29 19:44
门头沟学院 Java
wish233:很强了,加上这个学历,一点小建议就是可以把你的项目做一个压测,比如说你的RPC,可以对比一下和http相比性能怎么样。还有你的秒杀,一定要自己压测一遍,确保不会出现数据不一致的问题。还有就是对于分布式锁的粒度一定要理清楚,这个很容易被问到。
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
10-02 19:29
已编辑
浙江科技大学 运营
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务