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

 

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

ab*cde/-f*+
 1 #include<iostream>

 2 #include<stdlib.h>

 3 #include<string.h>

 4 using namespace std;

 5 char zhan[100];

 6 int top=-1;

 7 int cmp(char ch)

 8 {

 9     if(ch=='+'||ch=='-')return 1;

10     if(ch=='*'||ch=='/')return 2;

11     if(ch=='(')return 3;

12 }

13 void ruzhan(char ch)

14 {

15     zhan[++top]=ch;

16 }

17 int main()

18 {

19     char f[100];

20     cin>>f;

21     //while(cin>>f)

22     {

23         char bds[100];

24         int t=-1;

25         int i;

26         for(i=0; f[i]!='#'; i++)

27         {

28             if((f[i]>='0'&&f[i]<='9')||(f[i]>='a'&&f[i]<='z'))

29                 bds[++t]=f[i];

30             else

31             {

32                 if(f[i]=='(')

33                     ruzhan(f[i]);

34                 else if(f[i]==')')

35                 {

36                     for(; zhan[top]!='('; top--)

37                         bds[++t]=zhan[top];

38                     top--;

39                 }

40                 else

41                 {

42                     if(cmp(zhan[top])<cmp(f[i]))

43                     ruzhan(f[i]);

44                     else

45                     {

46                         while((cmp(zhan[top])>=cmp(f[i]))&&zhan[top]!='(')

47                         {

48                             bds[++t]=zhan[top];

49                             top--;

50                         }

51                         ruzhan(f[i]);

52                     }

53                 }

54             }

55         }

56         //cout<<top<<zhan[top]<<endl;

57         for(;top>=0;top--)

58         bds[++t]=zhan[top];

59         int j;

60         for(j=0;j<=t;j++)

61         cout<<bds[j];

62         cout<<endl;

63     }

64     return 0;

65 }

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

 

 
 
 
 

你可能感兴趣的:(数据结构)