5 用兩個棧實現佇列
阿新 • • 發佈:2018-11-22
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()){
if(stack1.empty()) return 0;
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
入隊:將元素進棧A
出隊:首先判斷棧B是否為空,若棧B為空,將棧A中的元素全部壓入棧B(若棧A中沒有元素,直接返回),再pop出棧B的棧頂元素,若棧B非空,直接pop出棧B的棧頂元素。