后缀表达式+栈(详解)(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 小时前
More Effective C++ 条款01:仔细区别 pointers 和 references
c++
工藤新一¹3 小时前
C/C++ 数据结构 —— 树(2)
c语言·数据结构·c++·二叉树··c/c++
源远流长jerry3 小时前
STM32之DMA详解
linux·网络·c++·stm32·单片机·嵌入式硬件
是店小二呀3 小时前
【C++】智能指针底层原理:引用计数与资源管理机制
android·java·c++
FirstFrost --sy5 小时前
map和set的使⽤
c++·set·map
不午睡的探索者5 小时前
FFmpeg + WebRTC:音视频开发的两大核心利器
c++·github·音视频开发
愚润求学5 小时前
【贪心算法】day3
c++·算法·leetcode·贪心算法
SimpleUmbrella5 小时前
windows下配置lua环境
c++·lua
重启的码农8 小时前
Windows虚拟显示器MttVDD源码分析 (6) 高级色彩与HDR管理
c++·windows·操作系统
jingfeng5148 小时前
C++多态
开发语言·c++