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

来源:互联网 发布:怎样快速提高淘宝等级 编辑:程序博客网 时间:2024/06/10 06:31

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

Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Example Input
59*684/-3*+#
Example Output
57
Hint
基本操作数都是一位正整数!

思路:读到操作符,出栈pop前两个,进行运算。运算完在入栈push,注意运算时的顺序:先出栈的是作为后一个操作数哦~

#include <stdio.h>#include <stdlib.h>#include <bits/stdc++.h>#define stackmax 10000  //存储空间初始分配量#define stacknum 10  //存储空间分配增量using namespace std;typedef int selemtype;  //栈里是char类型的typedef struct{    selemtype *base; //栈底指针    selemtype *top;  //栈顶指针    int stacksize;} sqstack;int Initstack(sqstack &S){    S.base=(selemtype *)malloc(stackmax*sizeof(selemtype));    if (! S.base)        return 0;  //存储分配失败    S.top=S.base;  //空栈条件    S.stacksize=stackmax;  //栈的存储空间    return 1;}int push(sqstack &S, selemtype e){    if(S.top-S.base>=S.stacksize)  //栈满,追加存储空间    {        S.base=(selemtype *)realloc(S.base,(S.stacksize+stackmax)*sizeof(selemtype));        if(!S.base)            return 0;        S.top=S.base+S.stacksize;        S.stacksize += stacknum;    }    *(S.top)=e;    S.top++;    return 1;}int pop(sqstack &S, selemtype &e)  //出栈,并将值赋值给e,所以&e{    if(S.top==S.base)        return 0;    e=*(S.top-1);    S.top--;    return 1;}int GetTop(sqstack S, selemtype &e){    if(S.top==S.base)    return 0;    e=*(S.top-1);    return 1;}int main(){    sqstack S;    Initstack(S);    int e1,e2;    char s[10005];    int i=0;    scanf("%s",s);  //字符串输入不加&    while(s[i]!='#')    {        if(s[i]>='0'&&s[i]<='9')  //整数范围        {            push(S,s[i]-'0'); //把字符型转化成整形        }        else        {            if(s[i]=='+')            {                 pop(S,e1);                 pop(S,e2);                 push(S,e1+e2);            }            else if(s[i]=='-')            {                pop(S,e1);                 pop(S,e2);               push(S,e2-e1);            }            else if(s[i]=='*')            {                pop(S,e1);                 pop(S,e2);                 push(S,e1*e2);            }            else if(s[i]=='/')            {                pop(S,e1);                 pop(S,e2);                 push(S,e2/e1);            }        }        i++;    }   GetTop(S,e1);   cout<<e1<<endl;    return 0;}
阅读全文
0 0
原创粉丝点击