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

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

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

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

Sample Input

59*684/-3*+#

Sample Output

57

Hint
基本操作数都是一位正整数!
题解:
后缀式求值就是在后缀式的基础上,如果是操作数就让它进栈,若果是运算符,就从栈顶取出两个操作数与运算符运算后再放到栈顶,直到计算到最后即可得出结果。

#include <stdio.h>
#include <stdlib.h>
#define stackinitsize 100
#define stackcreat 10
#define ok 1
#define overflow -1
#define error -1
typedef int elemtype;
typedef struct
{
    elemtype *base;
    elemtype *top;
    int stacksize;

} sqstack;
int initstack(sqstack *s)
{
    s->base=(elemtype*)malloc(stackinitsize*sizeof(elemtype));
    if(!s->base)exit(overflow);
    s->top=s->base;
    s->stacksize=stackinitsize;
    return ok;

}
int push(sqstack *s,elemtype e)
{
    if(s->top-s->base>=s->stacksize)
    {
        s->top=(elemtype*)realloc(s->base,(s->stacksize+stackcreat)*sizeof(elemtype));
        if(!s->base)exit(overflow);
        s->top=s->base+s->stacksize;
    }
    *s->top++=e;
    return ok;

}
int pop(sqstack *s)
{
    if(s->top==s->base)return error;
    s->top--;
    return ok;

}
int stackempty(sqstack *s)
{
    if(s->top==s->base)return 1;
    else return 0;

}
int gettop(sqstack *s)
{
    int e;
    if(s->top==s->base)return error;
    e=*(s->top-1);
    return e;
}

int main()
{
    char c;
    int e,e1,e2;
    sqstack s;
    initstack(&s);
    while(scanf("%c",&c)!=EOF)
    {
        if(c!='#')
        {
            if(c>='0'&&c<='9')
            {
                c=c-'0';
                push(&s,c);

            }

            else if(c=='+'||c=='-'||c=='*'||c=='/')
            {
                e1=gettop(&s);
                pop(&s);
                e2=gettop(&s);
                pop(&s);
                if(c=='+')e=e1+e2;
                if(c=='-')e=e2-e1;
                if(c=='*')e=e2*e1;
                if(c=='/')e=e2/e1;
                push(&s,e);


            }
        }

        if(c=='#')
        {
            e=gettop(&s);
            printf("%d\n",e);
            break;
        }


    }

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值