下面代码仅供本人复习数据结构所用,实用性N低,各位飘过吧~~哈哈:>
// // C++ 模版技术实现简单链式栈. // #include <cstdlib> #include <iostream> #include <iomanip> #include <stdexcept> // 链式栈类模版前置声明. template <typename T> class LinkedStack; // // 链式栈节点类模版. // template <typename T> class Node { friend class LinkedStack<T>; private: T _value; Node<T> *_pNext; public: Node(void) :_pNext(NULL) { NULL; } Node(const T &val) : _value(val) , _pNext(NULL) { NULL; } }; // // 链式栈类模版. // template <typename T> class LinkedStack { private: Node<T> *_pTop; public: LinkedStack(void); ~LinkedStack(void); bool isEmpty(void) const; T getTop(void) const; void push(const T &val); T pop(void); }; template <typename T> inline LinkedStack<T>::LinkedStack(void) : _pTop(NULL) { NULL; } template <typename T> LinkedStack<T>::~LinkedStack(void) { Node<T> *pDel = NULL; while (NULL != _pTop) { pDel = _pTop; _pTop = _pTop->_pNext; delete pDel; } } template <typename T> inline bool LinkedStack<T>::isEmpty(void) const { return NULL == _pTop; } template <typename T> inline T LinkedStack<T>::getTop(void) const { if (isEmpty()) { throw std::underflow_error("栈空下溢."); } return _pTop->_value; } template <typename T> inline void LinkedStack<T>::push(const T &val) { Node<T> *pNew = new Node<T>(val); pNew->_pNext = _pTop; _pTop = pNew; } template <typename T> inline T LinkedStack<T>::pop(void) { if (isEmpty()) { throw std::underflow_error("栈空下溢."); } T value = _pTop->_value; Node<T>* pDel = _pTop; _pTop = _pTop->_pNext; delete pDel; return value; } // // 测试栈. // int main(void) { const size_t MAX_SIZE = 20; LinkedStack<int> stack; std::cout << "栈" << (stack.isEmpty() ? "" : "不") << "为空." << std::endl; for (size_t i = 0; i < MAX_SIZE; ++i) { stack.push(i); std::cout << std::setw(3) << stack.getTop(); } std::cout << std::endl; std::cout << "栈" << (stack.isEmpty() ? "" : "不") << "为空." << std::endl; for (size_t i = 0; i < MAX_SIZE; ++i) { std::cout << std::setw(3) << stack.pop(); } // std::cout << std::setw(3) << stack.pop(); std::cout << std::endl; std::cout << "栈" << (stack.isEmpty() ? "" : "不") << "为空." << std::endl; return EXIT_SUCCESS; }