剑指offer[c++] 用两个栈实现队列
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路: push 比较容易,直接把数据push 进stack1中
pop需要将stack1中的数据push进stack2中,这样栈1的先入后出就可以变成栈2的先入先出,将栈2中的顶部数据返回即为队列的pop数据
再将栈2中的数据push回去栈1,保持原始状态。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int data;
int len1 = stack1.size();
while(len1>0)
{
data = stack1.top();
stack1.pop();
stack2.push(data);
len1--;
}
int res = stack2.top();
stack2.pop();
//int len2 = stack2.size();
while(stack2.size()>0)
{
data = stack2.top();
stack2.pop();
stack1.push(data);
//len2--;
}
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};