读书人

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

发布时间: 2013-01-26 13:47:01 作者: rapoo

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

Time Limit: 1000MS Memory limit: 65536K
题目描述对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。输入输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。输出求该后缀式所对应的算术表达式的值,并输出之。示例输入
59*684/-3*+#
示例输出
57

#include<cstdio>#include<stack>#include<cstring>using namespace std;int result(int a,int b,char c){ if(c=='*') return a*b; else if(c=='/') return a/b; else if(c=='-') return a-b; else if(c=='+') return a+b;}int main(){ char c[1001]; stack<int> S; while(scanf("%s",c)!=EOF) { while(!S.empty()) { S.pop(); } for(int i=0; i<strlen(c)-1; i++) { if(c[i]<='9'&&c[i]>='0') { int a=c[i]-'0'; S.push(a); } else { int a,b; b=S.top(); S.pop(); a=S.top(); S.pop(); int cc=result(a,b,c[i]); // printf("%d \n",cc); S.push(cc); } } int aa=S.top(); printf("%d\n",aa); } return 0;}

/************************************** Problem id : SDUT OJ D User name : ACboy Result : Accepted Take Memory : 1096K Take Time : 0MS Submit Time : 2013-01-23 12:07:45 **************************************/

读书人网 >编程

热点推荐