进阶实验3-3.1 求前缀表达式的值 (25分)--堆栈

 

 解题思路:(考虑小数,负数,以及多位整数)

从右向左扫描,遇到数字压栈,遇到运算符则弹出2个数,运算后再压栈,如此反复,直到处理完最后一个字符压栈后,栈顶所存即为求。

#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <math.h>
#define ERROR -1
#define ElemType double
typedef enum { false,true
             } bool;
typedef struct {
    ElemType *Data;
    int Top;
    int MaxSize;
}*Stack;
Stack CreateStack(int size) {
    Stack S=(Stack)malloc(sizeof(Stack));
    S->Data=(ElemType *)malloc(sizeof(ElemType)*size);
    S->MaxSize=size;
    S->Top=-1;
    return S;
}
bool IsEmpty(Stack S) {
    if(S->Top==-1)
        return true;
    return false;
}
bool IsFull(Stack S) {
    if(S->Top==S->MaxSize-1)
        return true;
    return false;
}
bool Push(Stack S,ElemType X) {
    if(IsFull(S))
        return false;
    S->Data[++S->Top]=X;
    return true;
}
ElemType Pop(Stack S) {
    if(IsEmpty(S))
        return ERROR;
    return S->Data[S->Top--];
}
ElemType GetTop(Stack S) {
    return S->Data[S->Top];
}
bool IsNum(char c) {
    if(c>='0'&&c<='9'||c=='.')
        return true;
    return false;
}
bool IsZF(char c) {
    if(c=='-'||c=='+')
        return true;
    return false;
}
bool IsOp(char c) {
    if(c=='-'||c=='+'||c=='/'||c=='*')
        return true;
    return false;
}
int main() {
    char c[31];
    gets(c);
    int len=strlen(c);
    int i,cnt=0,flag=0;
    Stack S=CreateStack(31);
    double sum=0.0;
    for(i=len-1; i>=0; i--) {
        if(IsNum(c[i])) {
            if(c[i]!='.') {
                sum+=(c[i]-'0')*pow(10,cnt);
                cnt++;
            } else {
                sum/=pow(10,cnt);
                cnt=0;
            }
            if(c[i-1]==' ') {
                Push(S,sum);
                cnt=0;
                sum=0.0;
            }
            if(IsZF(c[i-1])) {
                if(c[i-1]=='-')
                    sum=-1*sum;
                Push(S,sum);
                sum=0.0;
                i--;
            }

        } else if(IsOp(c[i])) {
            double x=Pop(S);
            double y=Pop(S);
            if(c[i]=='-') {
                sum=x-y;
            } else if(c[i]=='+') {
                sum=x+y;
            } else if(c[i]=='*') {
                sum=x*y;
            } else if(c[i]=='/') {
                if(y==0) {
                    flag=1;
                    break;
                }
                sum=x/y;
            }
            Push(S,sum);
            sum=0;
        }
    }
    if(!flag)
        printf("%.1lf",Pop(S));
    else
        printf("ERROR");
    return 0;
}

 

posted @ 2020-03-07 21:29  跃鱼  阅读(585)  评论(0编辑  收藏  举报