算术表达式的转换

来源:互联网 发布:淘宝分期购物 编辑:程序博客网 时间:2024/05/16 10:21

注意前缀后缀关于优先级的压栈问题

Problem Description

小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。
   因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。

Input

 输入一算术表达式,以\'#\'字符作为结束标志。(数据保证无空格,只有一组输入)

Output

 输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。

Example Input

a*b+(c-d/e)*f#

Example Output

+*ab*-c/defa*b+c-d/e*fab*cde/-f*+
#include<stdio.h>#include<stdlib.h>#include<string.h>typedef char SElemType;typedef struct{    SElemType *data;    int top;}SqStack;void creat(SqStack &L){    L.data = (SElemType *) malloc(1000 *sizeof(SElemType));    L.top = -1;}void Q(char s[], int l, SqStack &L) //思路来源:大话数据结构{    int i;    char b[1005];    int j = 0;    for(i = l - 1; i >= 0; i--)    {        if(s[i] >= 'a' && s[i] <= 'z')            b[j++] = s[i];        else if(L.top == -1)            L.data[++L.top] = s[i];        else if(s[i] == ')' || s[i] == '*' || s[i] == '/')            L.data[++L.top] = s[i];        else if(s[i] == '(')        {            while(L.data[L.top] != ')')            {                b[j++] = L.data[L.top];                L.top--;            }            L.top--;        }        else // +/-        {            while((L.data[L.top] == '*') || (L.data[L.top] == '/'))            {                b[j++] = L.data[L.top--];            }            L.data[++L.top] = s[i];        }    }    while(L.top >= 0)        {            b[j++] = L.data[L.top--];        }    j--;    while(j >= 0)        printf("%c", b[j--]);    printf("\n");    L.top = -1;}void Z(char s[]){    int i;    for(i = 0; s[i]; i++)        {            if((s[i] == '(' )||( s[i] == ')'))        ;    else        printf("%c", s[i]);        }    printf("\n");}void H(char s[], SqStack &L){    L.top = -1; /* 栈顶初值 */    /* 思路来源:《大话数据结构》 */    int i;    for(i = 0; s[i]; i++)    {        char x;        x = s[i];if(x >= 'a' && x <= 'z')printf("%c", x);        else if(L.top == -1 || x == '('){L.top++;L.data[L.top] = x;}else if(x == ')'){while(L.data[L.top] != '('){printf("%c", L.data[L.top--]);}L.top--;}else if(x == '*' || x == '/'){while(1){if(L.top == -1){L.data[++L.top] = x;break;}else if(L.data[L.top] == '*' || L.data[L.top] == '/')printf("%c", L.data[L.top--]);else{L.data[++L.top] = x;break;}}}else{while(1){if(L.top == -1){L.data[++L.top] = x;break;}else if(L.data[L.top] == '('){L.data[++L.top] = x;break;}else                printf("%c", L.data[L.top--]);}}    }    while(L.top != -1)    {        printf("%c", L.data[L.top--]);//输出剩余栈顶    }    printf("\n");}int main(){    int l;    char s[1005];    SqStack L;    creat(L);    gets(s);    l = strlen(s);    s[l - 1] = '\0';    l -= 1;    Q(s, l, L);    Z(s);    H(s, L);    return 0;}