SDUT2132算术表达式转换成后缀式(表达式树)

题目链接

解题报告:

这是很久前做的了。。又扒出来了。。怕再忘了嘛。。

很简单。建立表达式树,然后后序遍历。

代码如下:

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <ctype.h>  
  
#define MAXN 200  
  
int comp(char a, char b);  
  
int st1[MAXN], st2[MAXN];  
  
int main(){  
    int top1 = 0, top2 = 0, i=0;  
    char s[MAXN];  
    scanf("%s", s);  
    while(s[i] != '#'){  
        if(isalpha(s[i])) st1[top1++] = s[i];  
        else if(top2 == 0) st2[top2++] = s[i];  
        else if(s[i] == '(') st2[top2++] = s[i];  
        else if(s[i] == ')'){  
            while(st2[top2-1] != '(') st1[top1++] = st2[--top2];  
            --top2;  
        }  
        else if(comp(st2[top2-1], s[i])){  
            st1[top1++] = st2[--top2]; st2[top2++] = s[i];  
        }  
        else{  
            st2[top2++] = s[i];  
        }  
        i++;  
    }  
    while(top2 != 0){  
        st1[top1++] = st2[--top2];  
    }  
    for(i=0; i<top1; i++) putchar(st1[i]);  
    putchar('\n');  
    return 0;  
}  
  
int comp(char a, char b){  
    if(a == '(') return 0;  
    if(a=='*' || a=='/') return 1;  
    else if((a=='+' || a=='-') && (b == '+' || b == '-')) return 1;  
    else return 0;  
}  
原文地址:https://www.cnblogs.com/tanhehe/p/2916514.html