下面代码仅供本人复习数据结构所用,实用性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; }
原文链接: https://www.cnblogs.com/wxxweb/archive/2011/05/27/2059411.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/26245
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!