数据结构实验之栈与队列三:后缀式求值

数据结构实验之栈与队列三:后缀式求值

Description

对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。

Input

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

Output

求该后缀式所对应的算术表达式的值,并输出之。

Sample

Input 

59*684/-3*+#

Output 

57

Hint

基本操作数都是一位正整数!

 1     #include<stdio.h>
 2     #include<string.h>
 3     int top=0,i,b[1000];
 4     int main()
 5     {
 6         char s;
 7         while(scanf("%c",&s),s!='#')
 8         {
 9             if(s>='0'&&s<='9')
10             {
11                 b[++top]=s-'0';
12             }
13             else if(s=='+'||s=='-'||s=='*'||s=='/')
14             {
15                 if(s=='+')
16                 {
17                     b[top-1]=b[top-1]+b[top];
18                     top--;
19                 }
20                 if(s=='-')
21                 {
22                    b[top-1]=b[top-1]-b[top];
23                     top--;
24                 }
25                 if(s=='*')
26                 {
27                     b[top-1]=b[top-1]*b[top];
28                     top--;
29                 }
30                 if(s=='/')
31                 {
32                     b[top-1]=b[top-1]/b[top];
33                     top--;
34                 }
35             }
36         }
37         printf("%d\n",b[top]);
38         return 0;
39     }

 

posted on 2020-02-23 16:18  llllIYIlIN  阅读(329)  评论(0编辑  收藏  举报

导航