用两个栈实现队列

用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

stack1用来push, stack2用来pop

版本一: 每次pop操作都需要从stack1复制到stack2中, 并清空stack1, 其实在stack2不为空时, 执行pop操作不需要复制与清空操作

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

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

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

版本二: 当stack2不为空时, pop操作不清空stack1, 否则执行复制操作, 并清空stack1

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

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

private:
    stack<int> stack1;
    stack<int> stack2;
};
posted @ 2019-02-22 00:23  张飘扬  阅读(1004)  评论(0编辑  收藏  举报