{面试题7: 使用两个队列实现一个栈}

From 剑指Offer 何海涛 著

#include <iostream>
#include <exception>
#include <queue>

template <typename T>
class CStack {
    public:
        CStack(void);
        ~CStack(void);
        
        T& top(void);
        void push(const T&);
        void pop(void);
        
    private:
        std::queue<T> queue1;
        std::queue<T> queue2;
};


template <typename T>
CStack<T>::CStack() {
    
}

template <typename T>
CStack<T>::~CStack() {
    
}

template <typename T>
T& CStack<T>::top() {
   if(queue1.empty()) {
       if(queue2.empty()) {
           throw std::exception();
       }
#if __cplusplus >= 201103L
       queue1.swap(queue2);
#else
       while(queue2.size() > 1) {
           T& t = queue2.front();
           queue1.push(t);
           queue2.pop();
       }
       T& t = queue2.front();
       queue1.push(t);
       queue2.pop();
       return t;
#endif
   }
   while(queue1.size() > 1) {
       T& t = queue1.front();
       queue2.push(t);
       queue1.pop();
   }
   T& t = queue1.front();
   queue2.push(t);
   queue1.pop();
   return t;
}

template <typename T>
void CStack<T>::push(const T& value) {
    if(queue1.empty()) {
#if __cplusplus >= 201103L
        queue1.swap(queue2);
#else
        queue2.push(value);
        return;
#endif
    }
    queue1.push(value);
    
}

template <typename T>
void CStack<T>::pop() {
    if(queue1.empty()) {
        if(queue2.empty()) {
            throw std::exception();
        }
#if __cplusplus >= 201103L
        queue1.swap(queue2);
#else
        while(queue2.size() > 1) {
            T& t = queue2.front();
            queue1.push(t);
            queue2.pop();
        }
        queue2.pop();
        return ;
#endif
    }
    while(queue1.size() > 1) {
        T& t = queue1.front();
        queue2.push(t);
        queue1.pop();
    }
    queue1.pop();
}

测试集:

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[]) {
    CStack<char> stack;
    
    try {
        stack.top();
    } catch(std::exception& e) {
        std::cout << "true" << std::endl;
    }
    
    stack.push('a');
    stack.push('b');
    stack.push('c');
    
    test(stack.top(), 'c');
    stack.pop();
    test(stack.top(), 'b');
    stack.push('d');
    test(stack.top(), 'd');
    stack.pop();
    stack.pop();
    stack.pop();

    try {
        stack.pop();
    } catch(std::exception& e) {
        std::cout << "true" << std::endl;
    }
    
    return 0;

}

 

posted @ 2015-04-19 19:44  long#long  阅读(137)  评论(0编辑  收藏  举报