后缀表达式+栈(详解)(c++)

前言

很抱歉,上一期没有介绍栈stack的用法,今天简要介绍一下,再讲讲后缀表达式,用stack栈做一些后缀表达式的练习。

栈stack是c++中系统给出的栈,有了它,就不用自己创建栈啦!

头文件

栈stack的头文件就是**#include <stack>**

创建

定义一个名叫a的字符串栈:stack<char> a;

定义一个名叫a的整数栈:stack<int> a;

以此类推

用法

在栈a的栈顶加入元素b:a.push(b)

删除栈a的栈顶元素:a.pop()

栈a的栈顶元素:a.top()

判断栈a是否为空:a.empty()

后缀表达式

我们做数学时,用的都是中缀表达式

那么,什么是中缀表达式呢?

如:2+3,(5+6+7)/2......这些都是中缀表达式。

后缀表达式,就是在中缀表达式的基础上,将数字提前,把符号往后放。

如:

2+3的后缀表达式是2 3 +

(5+6+7)/2的后缀表达式是5 6 7 + + 2 /

而中缀表达式转成后缀表达式的规则是:

1.操作数直接输出

2.操作符入栈前,弹出栈中优先级更高或相等的运算符

3.左括号(入栈,右括号)弹出栈内元素直到(

4.操作符优先级 *和/大于+和-

那么,你学会了吗?

中缀转后缀

中缀表达式转后缀表达式的方法已经说过了,直接上代码:

cpp 复制代码
#include <iostream>
#include <stack>

using namespace std;

int main()
{
	stack<char> a;
	int n = 0;
	string str;
	while(true)
	{
		cin>>str[n];
		if(str[n]=='.') break;
		n++;
	}
	string b;
	string tmp;
	int lb = 0;
	int lt = n;
	for(int i = 0;i<n;i++)
	{
		if(str[i]=='*'||str[i]=='/')
		{
			while(true)
			{
				if(a.empty()==true) break;
				if(a.top()=='+'||a.top()=='-'||a.top()=='(') break;
				b[lb++] = a.top();
				a.pop();
				lt--;
			}
			a.push(str[i]);
			tmp[lt++] = str[i];
		}
		else if(str[i]=='+'||str[i]=='-')
		{
			while(true)
			{
				if(a.empty()==true) break;
				if(a.top()=='(') break;
				b[lb++] = a.top();
				a.pop();
				lt--;
				a.push(str[i]);
				tmp[lt++] = str[i];
			}
			a.push(str[i]);
		}
		else if(str[i]=='('||str[i]==')')
		{
			
			if(str[i]=='(')
			{
				a.push(str[i]);
				tmp[lt++] = str[i];
			}
			else if(str[i]==')')
			{
				while(true)
				{
					if(a.empty()==true) break;
					if(a.top()=='(') break;
					b[lb++] = a.top();
					a.pop();
					lt--;
				}
				
				a.pop();
				lt--;
			}
		}
		else
		{
			b[lb++] = str[i];
		}
	}
	
	while(a.empty()!=true)
	{
		b[lb++] = a.top();
		a.pop();
	}
	for(int i = 0;i<lb;i++)
	{
		cout<<b[i]<<" ";
	}
	
	return 0;
}

后缀表达式求值

(输入以点为结束)

cpp 复制代码
#include <iostream>
#include <stack>

using namespace std;

int main()
{
	
	stack<int> a;
	while(true)
	{
		char ch;
		cin>>ch;
		if(ch=='.') break;
		if(ch>='0'&&ch<='9')
		{
			a.push((int)ch-48);
		}
		else if(ch!=' ')
		{
			int aa = a.top();
			a.pop();
			int bb = a.top();
			a.pop();
			if(ch=='*') a.push(aa*bb);
			else if(ch=='/') a.push(bb/aa);
			else if(ch=='+') a.push(aa+bb);
			else if(ch=='-') a.push(bb-aa);
		}
	}
	cout<<a.top();
	
	return 0;
}
相关推荐
持力行2 小时前
从C struct到C++中的class
c语言·c++
GIS阵地5 小时前
QgsRasterDataProvider 完整详解(QGIS 3.40.13 C++)
开发语言·c++·qt·开源软件·qgis
charlie1145141917 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
2501_914245937 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
米罗篮9 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
肖爱Kun9 小时前
C++设计策略模式
开发语言·c++·策略模式
2501_914245939 小时前
C语言与硬件交互:从GPIO到中断的嵌入式编程实践
c语言·单片机·交互
炸膛坦客10 小时前
单片机/C/C++八股:(二十四)编译文件( .bin 和 .hex ,包括 .elf 和 .axf )
c语言·c++·单片机
cpp_250111 小时前
P10098 [ROIR 2023] 地铁建设 (Day 2)
数据结构·c++·算法·贪心·二分答案·洛谷题解
hehelm12 小时前
IO 多路复用 — Reactor
linux·服务器·网络·数据库·c++