剑指Offer——(5)用两个栈实现队列

xiaoxiao2021-02-27  725

题目描述:

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

实现如下:

//栈:先进后出 队列:先进先出 //注意最后一个元素的转移优化 //两个队列实现一个栈 //stack1负责入栈,stack2负责出栈 class Solution { public: void push(int node) { stack1.push(node); } int pop() { int x = 0; if (!stack2.empty())//stack2不为空,说明有数据,可以直接pop { x = stack2.top(); stack2.pop(); } else { //否则将stack1中的除最后一个的其余数据先pop再依次push到stack2中 while (!stack1.empty()) { x = stack1.top(); if (stack1.size() == 1) { stack1.pop(); break; } else { stack1.pop(); stack2.push(x); } } } return x; } private: stack<int> stack1; stack<int> stack2; };
转载请注明原文地址: https://www.6miu.com/read-402.html

最新回复(0)