劍指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;
};