【数据结构】栈

要求:

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

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

代码实现:

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

执行结果:

相关推荐
水木兰亭2 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
June bug3 小时前
【软考中级·软件评测师】下午题·面向对象测试之架构考点全析:分层、分布式、微内核与事件驱动
经验分享·分布式·职场和发展·架构·学习方法·测试·软考
Jess073 小时前
插入排序的简单介绍
数据结构·算法·排序算法
老一岁3 小时前
选择排序算法详解
数据结构·算法·排序算法
freexyn4 小时前
Matlab自学笔记六十一:快速上手解方程
数据结构·笔记·matlab
ysa0510304 小时前
Dijkstra 算法#图论
数据结构·算法·图论
醇醛酸醚酮酯5 小时前
基于多线程实现链表快排
数据结构·链表
小张成长计划..7 小时前
数据结构-栈的实现
开发语言·数据结构
一只鱼^_9 小时前
基础算法合集-图论
数据结构·算法·深度优先·图论·广度优先·宽度优先·图搜索算法
小张成长计划..10 小时前
双向链表的实现
数据结构·链表