void push(const T& data) { s1.push(data); } void pop() { if (s1.empty() && s2.empty()) { cout << "The queue is empty"; } if (!s2.empty()) { s2.pop(); } else { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } }
看代碼,是否以爲很簡單。函數
T& Front() { assert(!s1.empty() || !s2.empty()); if (s2.empty()) { while (!s1.empty()) { s2.push(s1.top()); s1.pop(); } } return s2.top(); } T& Back() { assert(!s1.empty() || !s2.empty()); if (s1.empty() ) { while (!s2.empty()) { s1.push(s2.top()); s2.pop(); } } return s1.top(); }
最後附上本人的總體代碼,歡迎指正:spa
1 #include<stack> 2 template<typename T> 3 class QueueBy2Stack 4 { 5 public: 6 7 void push(const T& data) 8 { 9 s1.push(data); 10 } 11 void pop() 12 { 13 if (s1.empty() && s2.empty()) 14 { 15 cout << "The queue is empty"; 16 } 17 if (!s2.empty()) 18 { 19 s2.pop(); 20 } 21 else 22 { 23 while (!s1.empty()) 24 { 25 s2.push(s1.top()); 26 s1.pop(); 27 } 28 s2.pop(); 29 } 30 } 31 T& Front() 32 { 33 assert(!s1.empty() || !s2.empty()); 34 if (s2.empty()) 35 { 36 while (!s1.empty()) 37 { 38 s2.push(s1.top()); 39 s1.pop(); 40 } 41 } 42 return s2.top(); 43 } 44 T& Back() 45 { 46 assert(!s1.empty() || !s2.empty()); 47 if (s1.empty() ) 48 { 49 while (!s2.empty()) 50 { 51 s1.push(s2.top()); 52 s2.pop(); 53 } 54 } 55 return s1.top(); 56 } 57 size_t size() 58 { 59 return s1.size() + s2.size(); 60 } 61 bool empty() 62 { 63 if (s1.empty() && s2.empty()) 64 { 65 return true; 66 } 67 return false; 68 } 69 private: 70 stack<T> s1; 71 stack<T> s2; 72 };
文章做者:Mr_listening。 博客地址:http://www.cnblogs.com/MrListening/code