中缀表达式转后缀表达式
-
从左到右进行扫描,若为数字直接输出;
-
若为字符:<1> 若栈为空,直接入栈;
<2> 若该操作符优先级大于栈出口操作符的优先级,直接入栈;
<3>若优先级第于栈出口操作符的优先级,进行出栈操作;直到该操作符优先级大于栈出口操作符的优先级,再将该字符入栈; -
若为“(” 直接入栈;
-
若为“)”,出栈操作,直到遇到“(”,包括“(”;
-
若扫描完,栈中仍有字符,直接出栈;
-
下面给出代码;
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxsize 200
typedef struct stack{
int top;
char str[maxsize];
}Stack;
void Init(Stack *obj){
obj->top =-1;
return ;
}
int Empty(Stack *obj){
if(obj->top ==-1) return 1;
return 0;
}
int Full(Stack *obj){
if(obj->top ==maxsize-1) return 1;
return 0;
}
int Pop(Stack *obj,char *c){
if(Empty(obj)) return 0;
*c=obj->str [obj->top --];
return 1;
}
int Push(Stack *obj,char c){
if(Full(obj)) return 0;
obj->str [++obj->top ]=c;
return 1;
}
int choose(char c){
if(c=='+' || c=='-') return 1;
else if(c=='*' || c=='/') return 2;
else if(c==')') return 3;
else if(c=='(') return 0;
else return 0;
}
int main(){
Stack *obj=(Stack*)malloc(sizeof(Stack));
Init(obj);
char x[100];
gets(x);
int n=strlen(x);
for(int i=0;i<n;i++){
if('0'<=x[i] && x[i] <='9'){
printf("%c ",x[i]);
}
else if(x[i]=='('){
Push(obj,x[i]);
}
else if(x[i]==')'){
Push(obj,x[i]);
char w;
while(obj->top!=-1){
Pop(obj,&w);
if(w !='(' && w !=')'){
printf("%c ",w);
}
if(w=='(') break;
}
}
else {
if(choose(x[i])<= choose(obj->str [obj->top ])){
while(obj->top !=-1){
char w;
Pop(obj,&w);
if(w !='(' && w !=')'){
printf("%c ",w);
}
if(w=='(') break;
}
Push(obj,x[i]);
}
else Push(obj,x[i]);
}
}
while(obj->top !=-1){
char w;
Pop(obj,&w);
printf("%c ",w);
}
return 0;
}
谢谢浏览;