C++数据结构——链栈的实现
来源:互联网 发布:监控图纸设计软件 编辑:程序博客网 时间:2024/06/10 21:12
链栈的实现,其实是针对栈的元素的个数变化量很大的一种情况,使用数组的话有可能造成很大的数组浪费空间,这时使用链栈来动态伸长链栈就变得很优秀了
节点结构
#pragma oncetemplate<typename T>class Node {public: T data; Node<T> *next;};
类模板:
#pragma once#include<iostream>#include"Node.h"using namespace std;template<typename T>class Stack {public: Stack(); ~Stack(); bool Push(T x); //元素入栈 bool pop(T &element); //栈顶元素出栈 bool Getpop(T &element) { if (top != NULL) { element = top->data; return true; } return false; } //获取栈顶元素 bool Empty() { return top == NULL ? true : false; } //判空private: Node<T> *top;};template<typename T>Stack<T>::Stack() { top = NULL;}template<typename T>Stack<T>::~Stack() { while (top->next!=NUll) { Node<T> *temp = top; top = top->next; delete temp; temp = NUll; } delete top; top = NULL;}template<typename T>bool Stack<T>::pop(T &element) { if (top == NULL) { cout << "当前栈为空,无法再出栈" << endl; return false; } else { Node<T> *temp = top; element= temp->data; top = top->next; delete temp; temp = NULL; return true; }}template<typename T>bool Stack<T>::Push(T x) { Node<T> *s = new Node<T>; if (s==NULL) { return false; //内存申请失败,返回 } s->data = x; s->next = top; top = s; return true;}
代码简单测试:
#include<iostream>#include"Stack.h"using namespace std;void popStack(Stack<int> *MyStack);void getpop(Stack<int> *MyStack);int main() { Stack<int> *MyStack=new Stack<int>; int element = 0; getpop(MyStack); if (MyStack->Empty()) { cout << "当前栈空" << endl; } else { cout << "当前栈不为空" << endl; } /*入栈入五个元素,先入的元素会到栈底,最后入的元素会在栈顶*/ MyStack->Push(1); MyStack->Push(2); MyStack->Push(3); MyStack->Push(4); MyStack->Push(5); popStack(MyStack); if (MyStack->Empty()) { cout << "当前栈空" << endl; } else { cout << "当前栈不为空" << endl; } popStack(MyStack); popStack(MyStack); popStack(MyStack); popStack(MyStack); getpop(MyStack); return 0;}void popStack(Stack<int> *MyStack) { int element; if (MyStack->pop(element)) { cout << "当前出栈元素为:" << element << endl; } else { cout << "当前栈为空,无法再出栈" << endl; }}void getpop(Stack<int> *MyStack) { int element; if (MyStack->Getpop(element)) { cout << "栈顶元素为:" << element << endl; } else { cout << "当前栈为空,所以无栈顶元素!" << endl; }}
结果:
总结:当栈中的元素个数变化不大时,我们应该使用顺序栈(因为使用链栈时多出来的一个指针域也会浪费空间)
阅读全文
0 0
- 数据结构——链栈的实现(C语言)
- <数据结构>链栈的C语言实现
- 数据结构C 语言描述——实现栈的基本功能
- 《数据结构与算法分析》—栈的链表和数组实现(C语言)
- 数据结构——栈的动态实现(malloc/free)(C语言实现)
- 数据结构——栈的动态实现(brk/sbrk)(Unix C语言实现)
- 数据结构——单链表的实现——C语言版
- 数据结构——队列的链式实现(C语言)
- 数据结构——二叉查找树的详细实现(c++)
- C语言实现堆栈(栈)的数据结构
- 数据结构的C实现_顺序栈
- <数据结构>顺序栈的C语言实现
- [数据结构]C语言栈的实现
- 数据结构栈的C语言实现
- 【数据结构】顺序栈的实现(c++)
- 数据结构之栈的c语言实现
- [数据结构]栈的C语言简单实现
- C语言实现数据结构的链表
- 自然语言处理入门——白话机器翻译原理
- Spring事物的再回顾
- SpringMVC的DispatcherServlet详解
- PAT (Basic Level) Practise (中文)1033. 旧键盘打字(20)
- 使用OpenCV4android(一)
- C++数据结构——链栈的实现
- 文章标题
- stm8存储器结构
- 自然语言处理入门——白话情感分析原理
- 数据结构之——线性表(一)
- 为什么运算符重载返回值使用&?
- 异常的基本使用
- javascript图片库样例的html与js分离,以及兼容性优化
- 1、新手入手树莓派教程--安装系统