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

来源:互联网 发布:淘宝买家秀百度云 编辑:程序博客网 时间:2024/05/16 17:27

题目链接:点击打开链接

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

59*684/-3*+#

示例输出

57

提示

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

来源

 

 

代码实现:

#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;int s[110],top;int main(){    top=-1;    char a[110];    int n,m;    scanf("%s",a);    for(int i=0;a[i]!='#';i++)    {        if(a[i]>='0'&&a[i]<='9')            s[++top]=a[i]-48;///叔叔说由ASCII码值转换为正常数值要减去48        else        {            if(a[i]=='+')            {                n=s[top--];                m=s[top--];                int c=m+n;                s[++top]=c;            }            if(a[i]=='-')            {                n=s[top--];                m=s[top--];                int c=m-n;                s[++top]=c;            }            if(a[i]=='*')            {                n=s[top--];                m=s[top--];                int c=m*n;                s[++top]=c;            }            if(a[i]=='/')            {                n=s[top--];                m=s[top--];                int c=m/n;                s[++top]=c;            }        }    }    printf("%d\n",s[top]);    return 0;}


 

0 0
原创粉丝点击