栈的基本操作和实现C++模板类
来源:互联网 发布:单片机原理及应用pdf 编辑:程序博客网 时间:2024/06/01 08:47
1.基本概念
栈中的元素遵守“先进后出”的原则(LIFO,Last In First Out)
只能在栈顶进行插入和删除操作
压栈(或推入、进栈)即push,将数据放入栈顶并将栈顶指针加一
出栈(或弹出)即pop,将数据从栈顶删除并将栈顶指针减一
栈的基本操作有:pop,push,判断空,获取栈顶元素,求栈大小
2.构造栈
可以使用数组构造栈,也可以使用单向链表构造,我觉得使用单向链表更加灵活方便,下面的例子我使用单向链表来构造栈。
单向链表的头插法比较适合,链表头作为栈顶:
(1)节点的数据结构
template<class T>struct node{ T value; //储存的值 node<T>* next; node() :next(nullptr){} //构造函数 node(T t) :value(t), next(nullptr){}};
(2)用C++模板类实现栈stack类
/* A simple example for stack implemented by C++.*/template<class T>class myStack{protected: struct node { T value; node* next; node() :next(nullptr){}; node(T t) :value(t), next(nullptr){}; };private: int cnts; //入栈数量 node *head; //栈的头部public: myStack(){ cnts = 0; head = new node; } void stackPush(T arg); //入栈 T stackPop(); //出栈 T stackTop(); //获取栈顶元素 void printStack(); //打印栈 int counts(); //获取栈内元素个数 bool isEmpty(); //判断空};template<class T>void myStack<T>::stackPush(T arg){ node *pnode = new node(arg); //申请入栈元素的空间 pnode->next = head->next; head->next = pnode; cnts++;}template<class T>T myStack<T>::stackPop(){ if (head->next!=nullptr) { node* temp = head->next; head->next = head->next->next; T popVal = temp->value; delete temp; return popVal; }}template<class T>T myStack<T>::stackTop(){ if (head->next!=nullptr) { return head->next->value; }}template<class T>void myStack<T>::printStack(){ if (head->next != nullptr) { node* temp = head; while (temp->next != nullptr) { temp = temp->next; cout << temp->value << endl; } }}template<class T>int myStack<T>::counts(){ return cnts;}template<class T>bool myStack<T>::isEmpty(){ if (cnts) return false; else return true;}
原文链接http://www.cnblogs.com/whlook/p/6531760.html
0 0
- 栈的基本操作和实现C++模板类
- 【c++】模拟实现栈 类模板(Stack的基本操作)
- 栈的基本操作实现-c/c++
- C语言实现栈的基本操作
- 类模板实现复数运算的基本操作
- 栈和队列的基本操作实现
- 栈的实现和基本操作
- 顺序栈的九种基本操作和实现(数据结构C语言版清华大学严蔚敏)
- C语言 栈的基本操作 栈的实现
- 栈的基本操作(c链表实现)
- 用C语言实现链栈的基本操作
- C语言实现顺序栈的基本操作
- 链栈的基本操作实现(c语言)
- C语言实现顺序栈的基本操作
- 算法与数据结构-栈的基本操作C语言实现
- 基于单链表的列表基本操作 类C语言实现
- c实现队列的基本操作
- C实现单链表的基本操作笔记
- [LeetCode]283. Move Zeroes
- Spring:基于注解的Spring MVC(下)
- 多线程
- bzoj 2539: [Ctsc2000]丘比特的烦恼 (KM算法)
- 用于FUZZ测试的程序及其详解
- 栈的基本操作和实现C++模板类
- mysql
- Git Push 避免用户名和密码方法
- 终于知道cocos2dx的cocos studio是被谁做烂得
- Spring:基于注解的Spring MVC(上)
- 隐马尔科夫模型的应用实例:中文分词
- HDU4404 Worms(计算多边形和圆的重叠面积)
- Java 30道经典笔试题
- 音频的mixer