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

来源:互联网 发布:淘宝运费险怎么赔付25 编辑:程序博客网 时间:2024/06/14 23:50

题目描述

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

输入

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

输出

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

示例输入

59*684/-3*+#

示例输出

57

提示

基本操作数都是一位正整数!
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<malloc.h>#define stackmax 100#define Stacksize 10typedef int ET;/*�����类�*/typedef struct{    ET *top;    ET *base;    int stacksize;}Sq;/*建�空表*/int Intistack(Sq &S){    S.base=(ET *)malloc(stackmax*sizeof(ET));    if(!S.base)exit(-1);    S.top=S.base;    S.stacksize=stackmax;    return 1;}/*����*/int Push(Sq &S,ET e){    if(S.top-S.base>=S.stacksize)    {        S.base=(ET *)realloc(S.base,(S.stacksize+Stacksize)*sizeof(ET));        if(!S.base)exit(-1);        S.top=S.base+S.stacksize;        S.stacksize+=Stacksize;    }    *S.top++=e;    return 1;}/*����*/int Pop(Sq &S,ET &e){    if(S.top==S.base)return 0;    e=*--S.top;    return 1;}int main(){    char str[100000];    int i,n,a,b,e;    Sq S;    Intistack(S);    gets(str);    n=strlen(str);    for(i=0;i<n;i++)    {        if(str[i]=='#')            break;        if(str[i]>='0'&&str[i]<='9')            Push(S,str[i]-'0');        if(str[i]=='*')        {            Pop(S,b);            Pop(S,a);            e=a*b;            Push(S,e);        }        if(str[i]=='/')        {            Pop(S,b);            Pop(S,a);            e=a/b;            Push(S,e);        }        if(str[i]=='+')        {            Pop(S,b);            Pop(S,a);            e=a+b;            Push(S,e);        }        if(str[i]=='-')        {            Pop(S,b);            Pop(S,a);            e=a-b;            Push(S,e);        }    }    Pop(S,e);    printf("%d\n",e);    return 0;}

0 0
原创粉丝点击