【数据结构】NOJ008 逆波兰表达式

1. 题目

在这里插入图片描述
在这里插入图片描述

2. 代码

这一次的代码我完全没参考其他人的!而且AC得很顺利!(当然,幸好上课发呆的空隙听了一下讲,大概知道思路)

啊哈哈。。。但是代码写的确实不好看,果然还是应该单独判断优先级的。

//(a+b)*c

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main(){
	string str;
	char tmp;
	stack<char> fuhao;	//只为符号设置了栈,遇到字母等可以直接输出 
	cin >> str;
	int len = str.length();
	for(int i=0; i<len; i++){
		switch(str[i]){
			case '(':{
				fuhao.push(str[i]);
				break;
			}
			case ')':{
				while(true){	//将最近的一个左括号前的符号全部输出 
					tmp = fuhao.top();
					fuhao.pop();
					if(tmp == '('){
						break;
					}
					else{
						cout << tmp;
					}
				}
				break;
			}
			case '+':
			case '-': 
			{
				if(!fuhao.empty() && fuhao.top()!='('){	
					tmp = fuhao.top();
					fuhao.pop();
					cout << tmp;
				}
				fuhao.push(str[i]);
				break;
			}
			case '*':
			case '/':{
				if(!fuhao.empty()){
					tmp = fuhao.top();
					if(tmp == '*' || tmp == '/'){ 
						cout << tmp;
						fuhao.pop();
					}
				}
				fuhao.push(str[i]);
				break;
			}
			default:{
				cout << str[i];
				break;
			}
		}
	}
	if(!fuhao.empty()){
		cout << fuhao.top();
		fuhao.pop();
	}
	return 0;
}

下面用优先级做了一遍,用map键值对存储优先级,代码精简了很多。但是!最开始我把优先级赋值给错了,莫名其妙出现了好些不对的结果。

而且对于 ‘(’ 和 ‘)’ 是不输出的需要注意。很容易这个括号就让人摸不着头脑了。

//a+b*(c-d)-e/f
#include <iostream>
#include <stack>
#include <map>
#include <string>

using namespace std;

int main(int argc, char** argv) {
	string str;
	cin >> str;
	stack<char> fuhao;
	fuhao.push('#');	//将#入栈,设置其优先级最高 
	
	// 就用map存储优先级 
	map<char, int> mp = {{')', 1}, {'+', 2}, {'-', 2}, {'*', 3}, {'/', 3}, {'(', 1}, {'#', 0}};
	int len = str.length();
	
	char tmp;
	for(int i=0; i<len; i++){
		if(mp.count(str[i])){	//如果该符号在map中(即属于6种符号之一) 
			if(!fuhao.empty()){
				tmp = fuhao.top();
				while(mp[tmp] >= mp[str[i]] && str[i] != '('){
					if(tmp != '(' && tmp != ')'){
						cout << tmp;
					} 
//					cout << "pop: " << tmp << endl; 
					fuhao.pop();
					tmp = fuhao.top();
				}
			}
//			cout << "push: " << str[i] << endl;
			fuhao.push(str[i]);			
		}
		else{	//不属于符号,直接输出 
			cout << str[i];
		}
	}
	while(!fuhao.empty()){
		tmp = fuhao.top();
		if(tmp == '#'){
			break;
		}
		if(tmp != '(' && tmp != ')'){
			cout << tmp;
		}
//		cout << "pop: " << endl; 
		fuhao.pop();
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值