劍指Offer——用兩個棧實現隊列
阿新 • • 發佈:2017-10-27
http 用兩個棧 pty return div eight color urn bsp
題目描述:
用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
分析:
代碼:
1 class Solution { 2 public: 3 void push(int node) { 4 stack1.push(node); 5 } 6 7 int pop() { 8 if(stack2.empty()) { 9 while(!stack1.empty()) { 10 stack2.push(stack1.top());11 stack1.pop(); 12 } 13 } 14 int t = stack2.top(); 15 stack2.pop(); 16 return t; 17 } 18 19 private: 20 stack<int> stack1; 21 stack<int> stack2; 22 };
劍指Offer——用兩個棧實現隊列