C++ 使用单向链表实现Stack
2017-05-07 21:34
323 查看
使用单向链表实现栈结构是一种简单且容易理解的方式
1、首先要创建一个节点类或者是结构体,这个结构体包括了该节点的下一个节点和该节点的值
2、声明Stack类
5、测试结果
输入:1 2 3 4 5
输出:5 4 3 2 1
参考文章 http://blog.csdn.net/u013445530/article/details/43381833 http://blog.csdn.net/yzl_rex/article/details/6692500 http://blog.csdn.net/qq_15718789/article/details/52743278
1、首先要创建一个节点类或者是结构体,这个结构体包括了该节点的下一个节点和该节点的值
template struct node { T value; //储存的值 node* next; node() :next(nullptr) {} //构造函数 node(T t) :value(t), next(nullptr) {} };
2、声明Stack类
template<class T> class MyStack { public: //构造函数,包括一个起始的Node和元素个数
MyStack() { _length = 0;_headNode = new node<T>(); }; ~MyStack(); bool clear(); bool isEmpty(); int GetLength(); const T GetTop(); bool Push(const T elem); bool Pop(T &oPopValue); void printStack(); private: int _length; node<T> *_headNode; };3、实现类
template<class T> MyStack<T>::~MyStack() { while (!isEmpty()) Pop(); if (_headNode) delete _headNode; } template<class T> bool MyStack<T>::clear() { while(_headNode->next) { T elemtop; bool isuccess = Pop(elemtop); if (!isucc) { return false; } } return true; } template<class T> bool MyStack<T>::isEmpty() { if (!_length) { return true; } else return false; } template<class T> int MyStack<T>::GetLength() { return _length; } template<class T> const T MyStack<T>::GetTop() { if (_headNode->next != nullptr) { T pValue = _headNode->next->value; return pValue; } } template<class T> bool MyStack<T>::Push(const T elem) { node<T>* pNode = new node<T>(elem); //采用头插法,即pNode代替栈顶的,所以pNode的下一个应为head的下一个; pNode->next = _headNode->next; _headNode->next = pNode; _length++; return true; } template<class T> bool MyStack<T>::Pop(T &oPopValue) { if (_headNode->next!=nullptr) { node<T>* TopNode = _headNode->next; _headNode->next = TopNode->next(); oPopValue = TopNode->value; _length--; delete TopNode; return true; } else return false } template<class T> void MyStack<T>::printStack() { if (_headNode->next != nullptr) { node<T> *pNode = _headNode->next; cout << pNode->value << endl; while (pNode->next) { cout << pNode->next->value << endl; pNode = pNode->next; } } }4、上述实现了stack的基本功能,其他功能可以继续拓展,然后测试
int main() { MyStack<int> *opStack = new MyStack<int>(); int a; while (cin>>a) { opStack->Push(a); } opStack->printStack(); system("pause"); }
5、测试结果
输入:1 2 3 4 5
输出:5 4 3 2 1
参考文章 http://blog.csdn.net/u013445530/article/details/43381833 http://blog.csdn.net/yzl_rex/article/details/6692500 http://blog.csdn.net/qq_15718789/article/details/52743278
相关文章推荐
- 使用C++实现的单向循环链表
- 使用C++实现单向链表
- 使用C++实现的单向循环链表
- 使用C++实现单向链表
- 单向链表的C++实现
- 数据结构C++模板实现之----------------单向链表
- [04.28更新]C++ 单向链表的实现
- C++实现单向链表
- 使用C++结合文件操作和链表实现学生成绩管理系统
- 单向链表高效的实现栈类,不含链表头和尾节点~使用单项链表实现高效的队类,不含链表头和尾节点
- 使用内部单向链表实现的一个简单堆栈
- 数据结构学习系列三-单向循环链表(c++实现且应用模板)
- 简单单向链表(C++模版技术实现)
- C++建立单向链表链表头指针需要使用指针类型的引用参数?
- 使用单向循环链表实现字典操作 INSERT、DELETE 和 SEARCH
- C/C++基本数据结构:链表的基本使用和实现
- C++中单向链表的实现(类似C#)
- 用c++实现简单的单向链表
- 一个简单的C++的链表实现(使用类模板)
- 利用 C++ 单向链表实现队列