题目描述
中缀表达式是一个通用的算术或逻辑公式表示方法,操作符是以中缀形式处于操作数的中间(例:3 + 4),中缀表达式是人们常用的算术表示方法。后缀表达式不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行(不再考虑运算符的优先规则,如:(2 + 1) * 3 , 即2 1 + 3 *。利用栈结构,将中缀表达式转换为后缀表达式。(测试数据元素为单个字符)
输入
中缀表达式输出
后缀表达式样例输入
A+(B-C/D)*E样例输出
ABCD/-E*+#include<iostream> #include<cstring> #include<malloc.h> using namespace std; #define M 1000 typedef struct { char data[M]; int top; }stack; void initstack(stack*&s) { s=(stack*)malloc(sizeof(stack)); s->top=-1; } void push(stack*&s,char a) { s->top++; s->data[s->top]=a; } int empty(stack*s) { if(s->top==-1) { return 0; } return 1; } char gettop(stack*s) { return s->data[s->top]; } void pop(stack*&s) { s->top--; } int check(char a,char b) { if((a=='+'||a=='-')&&(b=='*'||b=='/')) { return 1; } return 0; } int main() { stack*s; initstack(s); char str[M]; cin>>str; int len=strlen(str); for(int i=0;i<len;i++) { if(str[i]!='('&&str[i]!='+'&&str[i]!='-'&&str[i]!='*'&&str[i]!='/'&&str[i]!=')') { cout<<str[i]; } else if(str[i]=='(') { push(s,str[i]); } else { if(empty(s)==0||gettop(s)=='(')//0为栈空 { push(s,str[i]); } else if(str[i]==')')//将(之后的全部弹出 { while(gettop(s)!='(') { cout<<gettop(s); pop(s); } pop(s);//除( } else { if(check(gettop(s),str[i])==1)//如果str[i]的优先级大于栈顶元素 { push(s,str[i]); } else { while(check(gettop(s),str[i])==1&&empty(s)==1) { cout<<gettop(s); pop(s); } } } } } while(empty(s)==1) { cout<<gettop(s); pop(s); } return 0; }
SWUST OJ1042: 中缀表达式转换为后缀表达式
最新推荐文章于 2023-03-09 15:09:58 发布