【数据结构】栈

要求:

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

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

代码实现:

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;
}

执行结果:

相关推荐
666HZ6664 小时前
数据结构2.0 线性表
c语言·数据结构·算法
余瑜鱼鱼鱼5 小时前
Java数据结构:从入门到精通(十二)
数据结构
源代码•宸8 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
一叶知秋069 小时前
数据结构-什么是队列?
数据结构·队列
Jasmine_llq9 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计
软件小滔9 小时前
Mac 上看图?从需求出发的功能匹配
经验分享·macos·mac·应用推荐
zhongvv9 小时前
对单片机C语言指针的一些理解
c语言·数据结构·单片机·指针·汇编语言
im_AMBER10 小时前
Leetcode 102 反转链表
数据结构·c++·学习·算法·leetcode·链表
软件小滔10 小时前
MacOS 26.0 网速监控我试了十几款,从系统API到可视化实现
经验分享·macos·mac·应用推荐
Xの哲學10 小时前
深入剖析Linux文件系统数据结构实现机制
linux·运维·网络·数据结构·算法