【数据结构】栈

要求:

熟悉栈的定义,栈的特点以及栈的基本操作。能够根据实际情况选择合适的存储结构,解决实际问题。

对任意给定的一个中缀算术表达式输出等价的后缀形式。

代码实现:

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

using namespace std;

int prio(char op) {                 //给运算符优先级排序
	int t;
	if (op == '*' || op == '/')
		t = 2;
	if (op == '+' || op == '-')
		t = 1;
	if (op == '(')
		t = 0;
	return t;
}
bool Trans(string &str,string &str1) {  
	stack<char> s;                 
	int i;
	for (i = 0; i<str.size(); i++) {
		if (str[i] >= '0' && str[i] <= '9') {   
			str1+=str[i];
		}
		else {                        
			if (s.empty())           
				s.push(str[i]);
			else if (str[i] == '(')  
				s.push(str[i]);
			else if (str[i] == ')') {  
				while (s.top() != '(') {  
					str1+= s.top();
					s.pop();
				}
				s.pop();                
			}
			else {
				while (prio(str[i]) <= prio(s.top())) { 
					str1+= s.top();
					s.pop();
					if (s.empty())     
						break;
				}
				s.push(str[i]);   
			}
		}
	}
	while (!s.empty()) {     
		str1+= s.top();
		s.pop();
	}
	return true;

}
int main() {                
	string in;
	string post;
	cout << "请输入中缀表达式" << endl;
	cin >> in;
	Trans(in,post);
	cout << "后缀表达式为" << post << endl;
	return 1;
}

执行结果:

相关推荐
YSL0701248 小时前
贪吃蛇小游戏---古法编程
数据结构·游戏程序
wujiuhsu8 小时前
图片里的简体中文怎么翻译成繁体?商品图、详情页和海报批量转换方法
经验分享·笔记
y1su8 小时前
Leetcode 动态规划 模板
java·数据结构·算法·leetcode·动态规划
蛋白界小百灵9 小时前
AAV载体包装与纯化技术全解析:从三质粒系统到衣壳定向进化
经验分享·生物技术·实验·卡梅德生物·科研实验
All for pursuit.9 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
suhan9 小时前
【数据结构】五、树:7.哈夫曼树、哈夫曼编码
数据结构·算法·排序算法
suhan10 小时前
【数据结构】五、树:6.平衡二叉树AVL
数据结构·算法·排序算法
suhan10 小时前
【数据结构】五、树:5.二叉排序树BST
数据结构·算法·排序算法
爱读书的小胖10 小时前
80. 删除有序数组中的重复项 II
java·数据结构·算法
小画家~11 小时前
vue3 里面的 itemList.reduce
前端·数据结构·算法