直接上代码, 解释有空补上, 随手写的, 有问题欢迎指出
1 #include <stack> 2 3 template <typename T> 4 class CStkQueue 5 { 6 public: 7 T queuePop(); 8 void queuePush(T value); 9 size_t queueSize(); 10 11 private: 12 std::stack<T> std_stack_push; 13 std::stack<T> std_stack_pop; 14 }; 15 16 17 template <typename T> 18 T CStkQueue<T>::queuePop() 19 { 20 if (!std_stack_pop.empty()) 21 { 22 T temp = std_stack_pop.top(); 23 std_stack_pop.pop(); 24 return temp; 25 } 26 27 while (std_stack_push.size() != 1) 28 { 29 std_stack_pop.push(std_stack_push.top()); 30 std_stack_push.pop(); 31 } 32 33 T temp = std_stack_push.top(); 34 std_stack_push.pop(); 35 return temp; 36 } 37 38 template <typename T> 39 void CStkQueue<T>::queuePush(T value) 40 { 41 if (!std_stack_pop.empty()) 42 { 43 std_stack_push.push(std_stack_pop.top()); 44 std_stack_pop.pop(); 45 } 46 47 std_stack_push.push(value); 48 } 49 50 template <typename T> 51 size_t CStkQueue<T>::queueSize() 52 { 53 return (std_stack_push.size() + std_stack_pop.size()); 54 }
简单测试一下
原文:https://www.cnblogs.com/TssiNG-Z/p/12219345.html