【C++数据结构】模板链栈
来源:互联网 发布:2017网络事件 编辑:程序博客网 时间:2024/06/08 04:16
Stack.h
template<class T>class Link {public: Link();public: T data = NULL; Link* next = nullptr;};template<class T>class CStack{public: CStack(); ~CStack();private: Link<T>* top = nullptr; Link<T>* end = nullptr;public: void Push(T data); // 压入栈 T Pop(void); // 压出栈 int GetLength(void); // 得到长度 T& At(int i); //返回第i个数据 若i大于length或小于0 则返回0};
Stack.cpp
#include "Stack.h"template<class T>Link<T>::Link(){}template<class T>CStack<T>::CStack(){}template<class T>CStack<T>::~CStack(){ while (nullptr != top) { Link<T>* node = top; top = top->next; delete node; node = nullptr; }}template<class T>void CStack<T>::Push(T data){ if (nullptr == top) { top = new Link<T>; top->data = data; top->next = nullptr; end = top; return; } Link<T>* newNode = new Link<T>; newNode->data = data; newNode->next = nullptr; end->next = newNode; end = newNode;}template<class T>T CStack<T>::Pop(void){ if (nullptr == top) { return NULL; } T reVal = end->data; if (top == end) { delete end; top = end = nullptr; return reVal; } Link<T>* node = top; while (node->next != end) { node = node->next; } Link<T>* tempNode = end; end = node; delete tempNode; tempNode = nullptr; // delete之后一定要设置指针为空 否则 前一个指针的->next 仍然指着这个被删掉的区域 return reVal;}template<class T>int CStack<T>::GetLength(void){ int length = 0; Link<T>* node = top; while (nullptr != node) { node = node->next; length++; } return length;}template<class T>T& CStack<T>::At(int index)//返回对象的引用{ T empty = NULL; int length = GetLength(); if (index >= length || index < 0) { return empty; } Link<T>* node = top; for (int i = 0; i < length; i++, node = node->next) { if (i == index) { return node->data; } }}
源.cpp
#include "Stack.h"#include "Stack.cpp" // 因为使用了模板void main() { CStack<int> s; for (int i = 0; i < 10; i++) { s.Push(i); } for (int i = 0; i < 10; i++) { cout << s.Pop() << endl; } system("pause");}
0 0
- 【C++数据结构】模板链栈
- 数据结构(c++)栈的模板类(使用链表实现)
- 数据结构之顺序栈(数组)C++(模板)
- [数据结构]栈的实现(c++/类模板)
- 数据结构之单循环链表C++(模板)
- <C/C++数据结构>双向链表(C++模板实现)
- [数据结构]链表的实现(c++/类模板)
- [数据结构]循环链表(c++/类模板)用例JosephRing
- 数据结构之单链表C++(模板)
- 数据结构之双链表C++(模板)
- 数据结构(C++)----单链表模板类
- 数据结构(c++)最小堆模板类
- 数据结构C语言链栈
- 数据结构学习系列五-顺序栈(c++实现且应用模板)
- 数据结构学习系列六-链式栈(c++实现且应用模板)
- 数据结构(C++)-用顺序结构实现的栈模板类
- C++,数据结构,单向链表的实现及简单运用,运用模板
- 数据结构(C++) 二叉树模板类<链表存储表示>
- 我学JUC之LockSupport
- N皇后问题
- 【学习笔记】6.包含多个段的程序
- Java从入门到精通阅读笔记(第4版)11
- CCF201612-2
- 【C++数据结构】模板链栈
- 递归函数理解
- Hexo搭建博客以及多端同步更新
- Android移动应用开发学习笔记(二)——用户注册
- iOS中的MD5加密方法
- hdu3790(最短路径问题)
- 如何让div层置顶
- C++中::双冒号的用法
- java类加载过程