{面试题7: 用两个栈实现队列}
From 剑指Offer 何海涛 著
#include <iostream> #include <stack>
#include <exception>
template<typename T> class CQueue { public: CQueue(void); ~CQueue(void); void appendTail(const T& node); T deleteHead(); private: std::stack<T> stack1; std::stack<T> stack2; }; template<typename T> CQueue<T>::CQueue() { } template<typename T> CQueue<T>::~CQueue() { } template<typename T> void CQueue<T>::appendTail(const T& node) { stack1.push(node); } template<typename T> T CQueue<T>::deleteHead() { if(stack2.empty()) { while(!stack1.empty()) { T& t = stack1.top(); stack2.push(t); stack1.pop(); } if(stack2.empty()) { throw std::exception(); } } T t = stack2.top(); stack2.pop(); return t; }
测试集:
template<typename T> void test(const T& actual, const T& expected) { std::cout << std::boolalpha << (actual == expected) << std::endl; } int main(int argc, char* argv[]) { CQueue<char> queue; queue.appendTail('a'); queue.appendTail('b'); queue.appendTail('c'); test(queue.deleteHead(), 'a'); queue.appendTail('d'); test(queue.deleteHead(), 'b'); test(queue.deleteHead(), 'c'); test(queue.deleteHead(), 'd'); try { queue.deleteHead(); } catch(std::exception &e) { std::cout << "true" << std::endl; } return 0; }