中缀表达式变成后缀表达式

来源:互联网 发布:人民币国际化指数数据 编辑:程序博客网 时间:2024/05/16 02:27

中缀表达式是一个通用的算术或逻辑公式表示方法,操作符是以中缀形式处于操作数的中间(例:3 + 4),中缀表达式是人们常用的算术表示方法。后缀表达式不包含括号,运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行(不再考虑运算符的优先规则,如:(2 + 1) * 3 , 即2 1 + 3 *。利用栈结构,将中缀表达式转换为后缀表达式。(测试数据元素为单个字符)

例如:

输入:A+(B-C/D)*E

输出:ABCD/-E*+

#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct node{    char data[500];    int top;}Stack;void change(char str[]){    int n;    n=strlen(str);    int i,j;    Stack *L;    L=(Stack *)malloc(sizeof(Stack));    L->top=-1;    char temp;    int t=0;    char ops[]={'+','-','*','/','(',')'};    for(i=0;i<n;i++)    {        t=0;        temp=str[i];        for(j=0;j<6;j++)        {            if(temp==ops[j])            {                t=1;                break;            }        }        if(t==0)        {            printf("%c",temp);        }        else        {            L->top++;            L->data[L->top]=temp;            if(temp==')')            {                L->top--;                while(L->data[L->top]!='(')                {                    printf("%c",L->data[L->top]);                    L->top--;                }                L->top--;            }        }    }    for(;L->top>=0;L->top--)    {        printf("%c",L->data[L->top]);    }}int main(){    char str[1000];    scanf("%s",str);    change(str);    return 0;}


0 0
原创粉丝点击