SDUT 2132 数据结构实验之栈二:一般算术表达式转换成后缀式

来源:互联网 发布:用户积分数据库设计 编辑:程序博客网 时间:2024/05/20 01:08

数据结构实验之栈二:一般算术表达式转换成后缀式
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

Input

输入一个算术表达式,以‘#’字符作为结束标志。

Output

输出该表达式转换所得到的后缀式。

Example Input

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

Example Output

ab*cde/-f*+

代码:

#include<stdio.h>#include<string.h>int main(){    int top, i, j, top1;    char s[110], a[110], s1[110];//用两个数组分别模拟两个栈一个是总栈,一个是存放运算符的栈    while(~scanf("%s", a))    {        top = 0;        top1 = 0;        for(i = 0; a[i] != '#'; i++){        if(a[i] >= 'a' && a[i] <= 'z')        {            s1[top1++] = a[i];//遇到字母直接入总栈        }        else if(a[i] == '(')        {            s[top++] = a[i];//遇到左括号直接入运算符栈        }        else if(a[i] == ')')//遇到右括号        {            while(s[top - 1] != '(')            {                s1[top1++] = s[top - 1];//将运算符栈直到左括号(不包括左括号)的运算符入总栈                top--;            }            top--;//除去左括号        }        else if(a[i] == '+' || a[i] == '-')//遇到加或者减        {            while(s[top - 1] != '(' && s[top - 1] != '+' && s[top - 1] != '-' && top != 0)//判断运算符栈顶是不是左括号,加号减号,或者该栈是不是空 如果不是,就将运算符栈顶加入总栈            {                s1[top1++] = s[top - 1];//运算符栈顶加入总栈                top--;            }            s[top++] = a[i];//否则将遇到的加或者减加入运算符栈        }        else if(a[i] == '*' || a[i] == '/')//遇到乘除运算符        {            s[top++] = a[i];//直接入运算符栈,等到遇到加减的时候它就可以出来了        }        }        for(j = top - 1; j >= 0; j--)        {            s1[top1++] = s[j];//将运算符里的全部入总栈        }        for(i = 0; i < top1; i++)        printf("%c", s1[i]);//输出总栈        printf("\n");    }    return 0;}
0 0
原创粉丝点击