C++数据结构——链栈(基本代码实现与案例)

2024-04-17 04:38

本文主要是介绍C++数据结构——链栈(基本代码实现与案例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一:基本代码实现

#include<iostream>
using namespace std;enum error_code {success, underflow
};struct node
{int data;node* next; // 指向下一结点
};class linkStack {
public:linkStack();~linkStack();bool empty()const;error_code get_top(int& x)const;error_code push(const int x);error_code pop();
private:int count;node* top; // 指向自己
};linkStack::linkStack()
{count = 0;top = NULL;
}linkStack::~linkStack()
{while (!empty()) pop();
}bool linkStack::empty()const {return count == 0;
}error_code linkStack::get_top(int& x)const
{if (empty()) return underflow;x = top->data;return success;
}error_code linkStack::push(const int x)
{node* s = new node;s->data = x;s->next = top;top = s;count++;return success;
}error_code linkStack::pop()
{if (empty()) return underflow;node* s = new node;s = top;top = s->next;delete s;count--;return success;
}bool ReferenceError(error_code a)
{if(a == underflow){cout << "underflow!" << endl;return false;}return success;
}int main()
{linkStack s;int top;for(int i = 0; i < 10; i++) // 入栈 ReferenceError(s.push(i));for(int i = 0; i < 3; i++) // 出栈 ReferenceError(s.pop());ReferenceError(s.get_top(top)); // 取栈顶cout << "栈顶元素:" << top << endl; return 0;
}

二:链栈案例

  • 案例一:设计算法将十进制转换为八进制
  • 案例二:符号"{“,”}“,”[“,”]“,”(“,”)"应该是互相匹配的,设计算法对以字符串形式读取的表达式S,判断其中的各括号是否是匹配的
  • 案例三:使用栈结构写一个能计算带括号的四则表达式表达式的计算器
#include<iostream>
using namespace std;enum error_code {success, underflow
};template <class T>
struct node
{T data;node<T>* next;
};template <class T>
class linkStack {
public:linkStack();~linkStack();bool empty()const;error_code getTop(T& x)const;error_code push(const T x);error_code pop();
private:T count;node<T>* top;
};template <class T>
linkStack<T>::linkStack()
{count = 0;top = NULL;
}template <class T>
linkStack<T>::~linkStack()
{while (!empty()) pop();
}template <class T>
bool linkStack<T>::empty()const {return count == 0;
}template <class T>
error_code linkStack<T>::getTop(T& x)const
{if (empty()) return underflow;x = top->data;return success;
}template <class T>
error_code linkStack<T>::push(const T x)
{node<T>* s = new node<T>;s->data = x;s->next = top;top = s;count++;return success;
}template <class T>
error_code linkStack<T>::linkStack::pop()
{if (empty()) return underflow;node<T>* s = new node<T>;s = top;top = s->next;delete s;count--;return success;
}bool ReferenceError(error_code a)
{if (a == underflow) {cout << "underflow!" << endl;return false;}return success;
}// 十进制转八进制
void transform()
{// 初始化题目条件 int num, result = 0;cout << "请输入要转化为八进制的十进制数:";cin >> num;// 初始化栈结构 linkStack<int>s;int top; // 开始运算 while(num != 0){s.push(num % 8);num /= 8;}while(!s.empty()){s.getTop(top);s.pop();result = result * 10 + top; }cout << "转成八进制为:" << result << endl;
}// 检验符号匹配
string symbol()
{// 初始化题目条件string s;cout << "请输入表达式S: ";cin >> s;int length;length = s.length();// 初始化栈结构linkStack<char>a;char top;// 开始运算for(int i = 0; i < length; i++){if(s[i] == '(' || s[i] == '[' || s[i] == '{')a.push(s[i]);if(s[i] == ')'){a.getTop(top);if(top == '(')a.pop();elsereturn "不匹配!!";}if(s[i] == ']'){a.getTop(top);if(top == '[')a.pop();elsereturn "不匹配!!";}if(s[i] == '}'){a.getTop(top);if(top == '{')a.pop();elsereturn "不匹配!!";} }return "匹配!!";
}// 计算器
int getRes(int a, int b, char c) // 计算
{  int result;switch(c){case '+': result = a + b;break;case '-': result = a - b;break;case '*': result = a * b;break;case '/': result = a / b;break;}return result;
}
int getPri(char a) // 获得优先级 
{if(a == ')')return 1; if(a == '+' || a == '-')return 2;if(a == '*' || a == '/')return 3;if(a == '(')return 4;elsecout << "输入错误!!" << endl;
}
void calculator()
{// 初始化题目条件string s;cout << "请输入计算式:";cin >> s;int i = 0, k = 1, num1, num2;char sign;// 初始化栈结构linkStack<int>num;int top_n;linkStack<char>oper;char top_o;// 开始计算if(s[(s.length() - 1)] != '='){cout << "算式请以 '=' 结尾";return;	} while(s[i] != '='){if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || s[i] == '(' || s[i] == ')'){l:if(!oper.empty()){oper.getTop(top_o);if(getPri(s[i]) > getPri(top_o) || top_o == '(')oper.push(s[i]);else{oper.getTop(top_o);if(top_o != '('){num.getTop(top_n);num1 = top_n;num.pop();num.getTop(top_n);  num.pop();num.push(getRes(top_n, num1, top_o));oper.pop();oper.getTop(top_o);if(top_o == '('){oper.pop();i++;continue;	}goto l;  	}}}if(oper.empty())oper.push(s[i]); k = 1;}else{if(k == 0){num.getTop(top_n);num.pop();num.push(top_n * 10 + s[i] - 48);	}if(k == 1){num.push(s[i] - 48);k = 0;}}i++;}num.getTop(top_n);num1 = top_n;num.pop();num.getTop(top_n);oper.getTop(top_o);cout << "计算结果为:" << getRes(top_n, num1, top_o) << endl;
}int main()
{// 十进制转八进制transform();// 检验符号匹配cout << symbol() << endl;// 计算器calculator();return 0;
}

更多相关内容大家可以前往我的个人博客浏览:eyes++的个人空间

这篇关于C++数据结构——链栈(基本代码实现与案例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/910800

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符