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

用两个栈实现队列

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

class Solution
{
public:
    void push(int node) {
        this -> stack1.push(node);

    }

    int pop() {
	  	// 每次出栈就是导出栈1最底层的数据,需要一次性将栈1的数据导入到栈2,再执行出栈操作,最后再将栈2的数据导回栈1等待下次入栈操作。
        while(!this -> stack1.empty()) {
            int node = this -> stack1.top();
            this -> stack2.push(node);
            this -> stack1.pop();
        }
        int res = this -> stack2.top();
        this -> stack2.pop();
        while(!this -> stack2.empty()) {
            int node = this -> stack2.top();
            this -> stack1.push(node);
            this -> stack2.pop();
        }
        return res;
    }

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

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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