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

来源:互联网 发布:php session用法 编辑:程序博客网 时间:2024/05/29 17:44


这道题的算法思想就是:当输入的字符是数字字符时,将它转换成整数并压入栈中;当输入的字符是操作符时,将栈中的栈顶的两个元素取出并用这个运算符计算,然后将这两个元素出栈,将它们的运算结果进栈;最后输出栈顶元素即可。

代码如下:

#include <stdio.h>
#include <malloc.h>
#define maxsize 10000
typedef struct{
    int data[maxsize];
    int top;
}Seqstack;
Seqstack *Initstack(){
    Seqstack *s;
    s=malloc(sizeof(Seqstack));
    s->top=-1;
    return s;
};
Seqstack *Pushstack(Seqstack *s,int e){
    if(s->top==maxsize-1)
        printf("OVERFLOW!");
    s->top++;
    s->data[s->top]=e;
    return s;
};
int main(){
    int d,m,p;
    Seqstack *n;
    n=Initstack();
    char str;
    while(scanf("%s",&str)!=EOF&&str!='#'){/*在codeblocks中,用%s输入;在OJ上,用%c输入;*/
        if(str=='+'||str=='-'||str=='*'||str=='/'){
            if(str=='+'){
                m=n->data[n->top];
                n->top--;
                p=n->data[n->top];
                n->top--;
                n=Pushstack(n,m+p);
            }
            else if(str=='-'){
                m=n->data[n->top];
                n->top--;
                p=n->data[n->top];
                n->top--;
                n=Pushstack(n,p-m);
            }
            else if(str=='*'){
                m=n->data[n->top];
                n->top--;
                p=n->data[n->top];
                n->top--;
                n=Pushstack(n,p*m);
            }
            else if(str=='/'){
                m=n->data[n->top];
                n->top--;
                p=n->data[n->top];
                n->top--;
                n=Pushstack(n,p/m);
            }
        }
        else{
            d=(int)str-48;
            n=Pushstack(n,d);
        }
    }
    printf("%d",n->data[n->top]);
    return 0;
}

0 0
原创粉丝点击