7-3 后缀式求值

7-3 后缀式求值

链接:题目详情 - 7-3 后缀式求值 (pintia.cn)

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;

struct OPND{
    double data;
    struct OPND* next;
};
typedef struct OPND* num;

num N;

num Makeempty(){
    num S;
    S=(num)malloc(sizeof(struct OPND));
    S->next=NULL;
    return S;
}

void numpush(double x){
    num p;
    p=(num)malloc(sizeof(struct OPND));
    p->data=x;
    p->next=N->next;
    N->next=p;
}

void numpop(){
    num p;
    p=N->next;
    N->next=p->next;
}

double turn(string str){
    int i,j=-1;
    for(i=0;i<str.size();i++){
        if(str[i]=='.'){
            j=i;
            break;
        }
    }
    double ans=0,x=1,y;
    if(j!=-1){
        x=1;
        for(i=j-1;i>0;i--){
            ans=ans+(str[i]-'0')*x;
            x=x*10;
        }
        y=0.1;
        for(i=j+1;i<str.size();i++){
            ans=ans+(str[i]-'0')*y;
            y=y/10;
        }
    }
    else{
        x=1;
        for(i=str.size()-1;i>0;i--){
            ans=ans+(str[i]-'0')*x;
            x=x*10;
        }
    }
    if(str[0]=='-') ans=ans*-1;//判断是否是负数
    else ans=ans+(str[0]-'0')*x;
    return ans;
}

void jisuan(char c){
    double x,y,ans;
    x=N->next->data;
    numpop();
    y=N->next->data;
    numpop();
    if(c=='/') ans=y/x;
    else if(c=='*') ans=y*x;
    else if(c=='+') ans=y+x;
    else if(c=='-') ans=y-x;
    numpush(ans);
}

void slove(){
    string str,str1;
    getline(cin,str);
    int i=0;
    for(i=0;i<str.size();i++){
        while(str[i]!=' '&&i<str.size()){
            str1.push_back(str[i]);
            i++;
        }
        if(str1!="+"&&str1!="-"&&str1!="*"&&str1!="/"){
            double x=turn(str1);
            numpush(x);
        }
        else{
            jisuan(str1[0]);
        }
        str1.clear();
    }
    printf("%.1lf",N->next->data);
}
int main(){
    N=Makeempty();
    slove();
}
全部评论

相关推荐

点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务