后缀表达式的计算

题目大概如上,主要就是运用栈来进行后缀式的计算 这里加一句:就是计算机处理基本的算术都是先转化为后缀式(逆波兰式)再进行计算的。栈在计算机内部的应用还是挺多的

mian.cpp

#include <iostream>
#include "suffix.h"
using namespace std;

int main() {
    bool A=0,B=0,C=0,D=0;
    stack obj(5);
    string n;
    while(cin>>n)
    {
        if(n=="+")  {
            if(obj.currentLength<2)   {obj.currentLength=2;break;}
            obj.data[obj.currentLength-1]=obj.data[obj.currentLength-1]+obj.data[obj.currentLength];
            obj.currentLength--; A=1;
        }
        if(n=="-")  {
            if(obj.currentLength<2)   {obj.currentLength=2;break;}
            obj.data[obj.currentLength-1]=obj.data[obj.currentLength-1]-obj.data[obj.currentLength];
            obj.currentLength--; B=1;}
        if(n=="*")  {
            if(obj.currentLength<2)   {obj.currentLength=2;break;}
            obj.data[obj.currentLength-1]=obj.data[obj.currentLength-1]*obj.data[obj.currentLength];
            obj.currentLength--;C=1;}
        if(n=="/")  {if(obj.currentLength<2)   {obj.currentLength=2;break;}
            if(obj.data[obj.currentLength]<0.5)   {obj.currentLength=5;break;}
            else{obj.data[obj.currentLength-1]=obj.data[obj.currentLength-1]/obj.data[obj.currentLength];
                obj.currentLength--;D=1;}}
        if(cin.get()=='\n')    break;
        if(obj.currentLength==obj.maxSize)  obj.doubleSpace();
        if(!A&&!B&&!C&&!D){ obj.data[obj.currentLength+1]=atoi(n.c_str());obj.currentLength++;}
        A=0;B=0;C=0;D=0;/*初始化*/

    }
    if(obj.currentLength==1) cout<<obj.data[1];
    else{cout<<"illegal";}
    return 0;
}

suffix.h

 //
// Created by 86186 on 2022/11/2.
//
#include <iostream>
#ifndef UNTITLED6_STACK_H
#define UNTITLED6_STACK_H
struct stack{
public:double* data;
    int* top;
    int currentLength=0;
    int maxSize;
    bool IsEmpty();
    stack(int i);
    ~stack();
    void doubleSpace();


};
#endif //UNTITLED6_STACK_H

suffix.cpp

 //
// Created by 86186 on 2022/11/2.
//
#include <iostream>
#include "suffix.h"
using namespace std;
stack::stack(int i) {
   data=new double[i];maxSize=i;
    }

void stack::doubleSpace() {
    double *tmp=data;
    data=new double [maxSize*2];
    for(int i=1;i<=currentLength;i++)
        data[i]=tmp[i];
    delete [] tmp ;
}
bool stack::IsEmpty() {
    return (currentLength==0);
}
stack::~stack()
{delete [] data;}

感觉有新意的地方就是开始的输入部分运用了while(cin>>a) 注意a是string类型的主要是为了方便读入null、+等符号 string这里比较万能 后面就是栈的一些基本的操作了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值