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

来源:互联网 发布:大拿韩代 知乎 编辑:程序博客网 时间:2024/05/21 19:13

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

Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

59*684/-3*+#

示例输出

57

 

 

#include <stdio.h>
#include <stdlib.h>
#define stackmax 10000
#define stacknum 10000
typedef int ElemType;
typedef struct
{
    ElemType *base;
    ElemType *top;
    int stacksize;
} SqStack;

int InitStack(SqStack &s)
{
    s.base = (ElemType*) malloc (stackmax*sizeof(ElemType));
    if (! s.base)
        exit(0);
    s.top = s.base;
    s.stacksize = stackmax;
    return 0;
}
int Push(SqStack &s , int e)
{
    if(s.top-s.base >= s.stacksize)
    {
        s.base = (ElemType *)realloc(s.base,(s.stacksize+stacknum)*sizeof(ElemType));
        if (! s.base ) exit(0);
        s.top = s.base + s.stacksize;
        s.stacksize += stacknum;
    }
    *s.top++=e;
}
void putstack(SqStack &s)
{
    while(s.top > s.base)
    {
        printf("%d", *(s.top-1));
        s.top--;
    }
    printf("\n");
}


int  Pop(SqStack &s)
{
    if(s.top == s.base)   return 0;
    s.top--;
    return 1;
}

int GetTop(SqStack &s)
{
    if(s.top == s.base)   return 0;
    int e=*(s.top-1);
    return e;
}

int operate(int a, char theta, int b)
{
    int e;
    if(theta=='+')
        e=a+b;
    if(theta=='-')
        e=b-a;
    if(theta=='*')
        e=b*a;
    if(theta=='/')
        e=b/a;

    return e;

}//注意b与a的运算次序


int evaluation(SqStack &s, char c)
{
    int a, b;
    if(c>='0'&&c<='9')
    {
        Push(s, c-'0');
    }
    else
    {

        a=GetTop(s);
        Pop(s);
        b=GetTop(s);
        Pop(s);
        Push(s, operate(a, c, b));
    }


}

int main()
{
    char c;
    SqStack s;
    InitStack(s);
    while(~scanf("%c", &c)&&c!='#')
    {
        evaluation(s, c);
    }

    printf("%d", *s.base);
}

0 0