解题思路
先进后出,再来一次先进后出,就变成后进先出了
include <iostream>
include <vector>
include <stack>
using namespace std;
class Solution
{
public:
void push(int node)
{
stack1.push(node);
}
int pop()
{
int val = -1;
if (stack1.empty() && stack2.empty())
{
return -1;
}
if (stack2.empty())
{
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
//stack2现在就是队列了
val = stack2.top();
stack2.pop();
return val;
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main()
{
Solution solu;
solu.push(1);
solu.push(2);
solu.push(3);
solu.push(4);
int node;
cout << solu.pop() << endl;
cout << solu.pop() << endl;
cout << solu.pop() << endl;
cout << solu.pop() << endl;
cout << system("pause");
return 0;
}
牛客网在线检验:用两个栈实现队列