刷題筆記(四)——利用棧實現隊列
題目描述
用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素爲int類型。
思路:一個棧stack1作爲push,將入隊的元素push到該棧中;另一個棧stack2作爲pop,出隊時,若該棧不爲空,則直接pop該棧中的元素,若爲空時,需先將stack1中的元素逐個pop,再push到stack2中。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int a;
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
a=stack2.top();
stack2.pop();
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};