C++数据结构与算法堆栈学习笔记(使用类模板)
2021/4/14 20:31:04
本文主要是介绍C++数据结构与算法堆栈学习笔记(使用类模板),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
基础介绍
数据结构
1. 软件 = 程序 + 文档
程序 = 数据结构 + 算法
2. 对于一个数据结构来讲,需要做到增删减查四个基本功能。
堆栈
堆栈是一种数据结构。堆栈都是一种数据项按序排列的数据结构,只能在一端(称为栈顶(top))对数据项进行插入和删除。
堆栈就像一个圆柱体的硬币盒(只开一边口),每次只能从顶部操作,后进先出,每次只能取得最顶部的一枚硬币。
模板类
在定义类之前,使用template<class Item>
获得一个模板
(item处可以自己命名,用于代替类型的名称)
——————————————————代码实现———————————————————
#include<iostream> enum Error_code{underflow,overflow,success}; //枚举元素来表示函数返回值 using namespace std; template<class Item> //模板 class Stack{ private: enum {MAX=50}; Item items[MAX]; int count; public: Stack(); //初始化 bool isempty() const; //堆栈是否为空 bool isfull() const; //堆栈是否满 Error_code push(const Item& item); //将item压入堆栈内 Error_code pop(); //弹出栈顶元素 Error_code Top(Item&item); //将栈顶元素赋值给item(不破坏内部结构) void clear(); //清空栈 }; template<class Item> //每次定义前都要使用模板代替不确定的类型 Stack<Item>::Stack() { count = 0; for (int i = 0; i < MAX; i++) items[i] = 0; } template<class Item> bool Stack<Item>::isempty() const { if (count != 0) return false; else return true; } template<class Item> bool Stack<Item>::isfull() const { if (count != MAX) return false; else return true; } template<class Item> Error_code Stack<Item>::push(const Item& item) { if (count < MAX) { items[count++] = item; return success; } else return overflow; } template<class Item> Error_code Stack<Item>::pop() { if (count > 0) { items[count] = 0; --count; return success; } else return underflow; } template<class Item> Error_code Stack<Item>::Top(Item&item) { if (count!=0){ item=items[count-1]; return success; } return underflow; } template<class Item> void Stack<Item>::clear() { while (count > 0){ pop(); } } //试试看 int main(){ int nums; Stack<int> testStack; for (int i =1;i<=5;i++){ testStack.push(i); } for (int i =1;i<=5;i++){ testStack.Top(nums); cout<<nums<<" "; testStack.pop(); } return 0; }```
这篇关于C++数据结构与算法堆栈学习笔记(使用类模板)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升