数据结构实验之栈三:后缀式求值SDUT2133

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

Time Limit: 1000MS Memory Limit: 65536KB

Submit Statistic

Problem Description

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

Input

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

Output

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

Example Input

59*684/-3*+#

Example Output

57

法1:

扫描二维码关注公众号,回复: 2573637 查看本文章

#include <stdio.h>

#include <stdlib.h>

int top=0,i,stack[1001];

int main() {

char a[1001]; scanf("%s",a);

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

{ if(a[i]>='1'&&a[i]<='9')

{

stack[++top]=a[i]-'0';

}

else if(a[i]=='+')

{ stack[top-1]=stack[top-1]+stack[top]; top--; }

else if(a[i]=='-')

{ stack[top-1]=stack[top-1]-stack[top]; top--; }

else if(a[i]=='*')

{ stack[top-1]=stack[top-1]*stack[top]; top--; }

else if(a[i]=='/')

{ stack[top-1]=stack[top-1]/stack[top]; top--; } }

printf("%d\n",stack[top]);

return 0;

}

法2:

  1. #include <iostream>

  2. #include <bits/stdc++.h>

  3. using namespace std;

  4. const int MAXN=10000+5;

  5. char s[MAXN];

  6. int st[MAXN];

  7. int get_value(int x,int y,char s)

  8. {

  9. if(s=='+')return x+y;

  10. if(s=='-')return x-y;

  11. if(s=='*')return x*y;

  12. return x/y;

  13. }

  14. int main()

  15. {

  16. int top=0;

  17. scanf("%s",s);

  18. int i=0;

  19. while(s[i]!='#')

  20. {

  21. if(isdigit(s[i]))st[top++]=s[i]-'0';

  22. else

  23. {

  24. int x=st[--top];

  25. int y=st[--top];

  26. st[top++]=get_value(y,x,s[i]);

  27. }

  28. i++;

  29. }

  30. printf("%d\n",st[0]);

  31. return 0;

  32. }

  33.  

猜你喜欢

转载自blog.csdn.net/Allinone99/article/details/81298851