剑指offer上的题目,因为我刚刚看过栈和队列,所以想练几个题目,再加强对栈和队列的认识。
其实还算简单。就是第一个栈用来push,第二个栈用来delete。代码如下:
#include<iostream>
#include<stack>
using namespace std;
class solution {
public:
void push(int x)
{
si1.push(x);
}
int pop()
{
if (si2.empty())
{
while (!si1.empty())
{
si2.push(si1.top());
si1.pop();
}
}
int top = si2.top();
si2.pop();
return top;
}
private:
stack<int> si1;
stack<int> si2;
};
int main()
{
solution queue;
queue.push(3);
queue.push(8);
queue.push(9);
int i1 = queue.pop();
cout << i1 << endl;
queue.push(99);
queue.push(22);
int i2 = queue.pop();
cout << i2 << endl;
return 0;
}