用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路很简单,stack1栈负责push, stack2栈负责pop, stack2这个栈空的时候,要把stack1的元素全部压入stack2
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include<stack>
#include<cmath>
#include<algorithm>
#include <iomanip>
using namespace std;
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()) {
while(!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
}
int res=-1;
if(!stack2.empty())
res=stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main()
{
Solution sol;
sol.push(2);
sol.push(1);
sol.push(0);
int res=sol.pop();
cout<<res<<endl;
system("pause");
return 0;
}
本文介绍了一种使用两个栈来实现队列的方法,详细解释了如何通过一个栈进行元素的压入(push),并通过另一个栈进行元素的弹出(pop)。当负责弹出的栈为空时,会将负责压入的栈的所有元素转移过来,从而实现了队列的先进先出(FIFO)特性。
1301

被折叠的 条评论
为什么被折叠?



