標籤:
用兩個棧實現隊列
- 參與人數:3047時間限制:1秒空間限制:32768K
- 通過比例:34.71%
- 最佳記錄:0 ms|0K(來自 青哥)
題目描述用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
思路1(最普通的方法):
1、入隊時,直接壓入到stack1中;
2、出隊時,先將stack1中的所有size-1個元素壓入stack2中,然後將stack1的元素彈出;最後將stack2中的元素重新壓入到s1中。
如所示:
1 class Solution 2 { 3 public: 4 void push(int node) { 5 stack1.push(node); 6 } 7 8 int pop() { 9 int t;10 while (stack1.size() > 1){11 t = stack1.top();12 stack2.push(t);13 stack1.pop();14 }15 int rt = stack1.top();16 stack1.pop();17 while(stack2.size() > 0){18 t = stack2.top();19 stack1.push(t);20 stack2.pop();21 }22 return rt;23 }24 25 private:26 stack<int> stack1;27 stack<int> stack2;28 };View Code
思路2(最佳化):
1、入隊時,直接壓入到stack1中;
2、出隊時,若stack2不為空白,則直接彈出;若stack2為空白,則將stack1的size-1個元素壓入stack2中,最後彈出stack1中的棧頂元素。
1 class Solution 2 { 3 public: 4 void push(int node) { 5 stack1.push(node); 6 } 7 8 int pop() { 9 int rt;10 if (!stack2.empty()){11 rt = stack2.top();12 stack2.pop();13 }14 else{15 while (stack1.size() > 1){16 rt = stack1.top();17 stack2.push(rt);18 stack1.pop();19 }20 rt = stack1.top();21 stack1.pop();22 }23 return rt;24 }25 private:26 stack<int> stack1;27 stack<int> stack2;28 };View Code
用兩個棧實現隊列