剑指Offer05 用栈模拟队列
添加了模板类应用
1 /************************************************************************* 2 > File Name: 05_StackMakeQueue.cpp 3 > Author: Juntaran 4 > Mail: JuntaranMail@gmail.com 5 > Created Time: 2016年08月29日 星期一 19时32分12秒 6 ************************************************************************/ 7 8 #include <stdio.h> 9 #include <bits/stdc++.h> 10 11 using namespace std; 12 13 template<class T> 14 class qStack 15 { 16 private: 17 stack<T> stack1; 18 stack<T> stack2; 19 int size; 20 21 public: 22 qStack() 23 { 24 size = 0; 25 } 26 void push(T &node) 27 { 28 stack1.push(node); 29 size = stack1.size(); 30 } 31 T pop() 32 { 33 assert(this->size > 0); 34 T ret = 0; 35 if (this->size == 1) 36 { 37 ret = stack1.top(); 38 stack1.pop(); 39 this->size = 0; 40 return ret; 41 } 42 if (this->size > 1) 43 { 44 while (stack1.size()) 45 { 46 stack2.push(stack1.top()); 47 stack1.pop(); 48 } 49 ret = stack2.top(); 50 stack2.pop(); 51 52 while (stack2.size()) 53 { 54 stack1.push(stack2.top()); 55 stack2.pop(); 56 } 57 this->size --; 58 return ret; 59 } 60 } 61 }; 62 63 64 int main() 65 { 66 qStack<int> quque; 67 for (int i = 0; i < 5; i++) 68 { 69 cout << i << " push" << endl; 70 quque.push(i); 71 } 72 for (int i = 1; i < 3; i++) 73 { 74 cout << quque.pop() << " pop" << endl; 75 } 76 for (int i = 5; i < 7; i++) 77 { 78 cout << i << " push" << endl; 79 quque.push(i); 80 } 81 for (int i = 1; i < 3; i++) 82 { 83 cout << quque.pop() << " pop" << endl; 84 } 85 cout << endl; 86 }