一、中缀转后缀
(1)流程
- 对输入的字符串的每一个字符左到右遍历,若字符是
操作数
操作符
- 判断栈空或栈顶元素是否为左括号
- 判断操作符与栈顶元素的优先级
(2)代码
#include <iostream>
#include <string.h>
using namespace std;
const int MAX_SIZE=10000;
int comparePriority(char ,char );
int main(){
int top=-1;
string input;
char stack[MAX_SIZE];
cin>>input;
for (int i=0;i<input[i]!='\0';i++){
char ch=input[i];
if (ch>='0'&&ch<='9'){
cout<<ch;
}
else if (ch=='+'||ch=='-'||ch=='*'||ch=='/'){
if (top==-1) stack[++top]=ch;
else
while (true){
if (top==-1||stack[top]=='(') {
stack[++top]=ch;
break;
}
if (comparePriority(ch,stack[top])==1){
stack[++top]=ch;
break;
}
else {
cout<<stack[top--];
continue;
}
}
}
else if (ch=='(')
stack[++top]=ch;
else if (ch==')'){
while (top!=-1&&stack[top]!='('){
cout<<stack[top--];
}
if (top!=-1) {
top--;
}
}
}
while (top!=-1){
cout<<stack[top--];
}
}
int comparePriority(char former,char latter){
if (former=='+'||former=='-'){
if (latter=='*'||latter=='/')
return -1;
else return 0;
}
else {
if (latter=='+'||latter=='-')
return 1;
else return 0;
}
}