单位数加减乘除
例如:2+3*(4-9)
定义一个栈内优先级
| 运算符号 | 优先级 | 
|---|---|
| +、- | 3 | 
| *、/ | 5 | 
| ( | 1 | 
| ) | 6 | 
| # | 0 | 
定义一个栈外优先级
| 运算符号 | 优先级 | 
|---|---|
| +、- | 4 | 
| *、/ | 2 | 
| ( | 6 | 
| ) | 1 | 
| # | 0 | 
整个过程如下:
首先将#入栈,这是为了让运算符与栈内的符号进行比较是否入栈,否则无法判断
- 2为数字,直接输出
 - +和#进行运算符比较,因为+的优先级大于#,入栈
 - 3为数字,直接输出
 - (和+进行比较,(的优先级比+大,将+取出输出,将(入栈
 - 4为数字,直接输出
 - -的优先级比’(‘大,直接入栈。注意:此时的’('为栈内优先级
 - 9为数字。直接输出
 - )优先级比-大,取出-,同时()配对了,也要将(取出
 - 最后遍历栈内运算符即可
 
需要注意的点是:
就像这样栈内的头顶两个元素这样(+,下一个符号刚好是),需要考虑到,取完+号后,需要把(也去取出来
实现代码
#include<iostream>
#include<stack>
#include<string>
using namespace std;
//栈内优先级
int CompareIn(char c){
	if(c=='('){
		return 1;
	}
	if(c=='+'||c=='-'){
		return 3;
	}
	if(c=='*'||c=='/'){
		return 5;
	} 
	if(c==')'){
		return 6;
	}
	if(c=='#'){
		return 0;
	}
}
//栈外优先级 
int CompareOut(char c){
	if(c=='('){
		return 6;
	}
	if(c=='+'||c=='-'){
		return 2;
	}
	if(c=='*'||c=='/'){
		return 4;
	} 
	if(c==')'){
		return 1;
	}
	if(c=='#'){
		return 0;
	}
}
int main(){
	string str;
	cin>>str;
	stack<char> q;
	q.push('#');
	for(int i=0;i<str.length();i++){		
		if('1'<=str[i]&&str[i]<='9'){
			cout<<str[i];
		}else{
			if(CompareIn(q.top())<CompareOut(str[i])){
				q.push(str[i]);
			}else if(CompareIn(q.top())==CompareOut(str[i])){
				q.pop();
			}else if(CompareIn(q.top())>CompareOut(str[i])){
				char ch=q.top();
				q.pop();
				cout<<ch;
				if(str[i]!=')'){
					q.push(str[i]);
				}	
			   if(CompareIn(q.top())==CompareOut(str[i])){
				q.pop();
		    	}
			}
		}
	}
	while(CompareIn(q.top())!=0){
		cout<<q.top();
		q.pop();
	}
	
}
}

	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
		
评论(0)