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

用两个栈实现队列

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

stack1用于出栈
stack2用于入栈

stack1出栈之前,stack2要全部挪入stack1
stack2入栈之前,stack1要全部挪入stack2

class Solution
{
public:
    //sour-->des
    void move(stack<int>& sour, stack<int>& des){
        while(!sour.empty()){
            int cur = sour.top();
            sour.pop();
            des.push(cur);
        }
    }
    void push(int node) {
        move(stack1, stack2);
        stack2.push(node);
    }

    int pop() {
        move(stack2, stack1);
        if(stack1.empty()) 
            return -1;
        int res = stack1.top();
        stack1.pop();
        return res;
    }

private:
    stack<int> stack1; //pop栈
    stack<int> stack2; //push栈
};
全部评论

相关推荐

码农索隆:以下是我以我微薄的认知提供的建议: 1.考个教师资格证,去当体育考试。 2.去健身房当健身教练(因为在我印象里面体育生身材都不错)。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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