3.1.5.1 后缀表达式计算

时间:2020-03-26
本文章向大家介绍3.1.5.1 后缀表达式计算,主要包括3.1.5.1 后缀表达式计算使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

LNode.h

#pragma once
class LNode
{
    friend class LinkStack;
    int data;
    LNode* next;
};

LinkStack.h

#pragma once
#include"LNode.h"
#include<iostream>
using namespace  std;
class LinkStack
{
private:
    LNode* top;
public:
    LinkStack();
    bool IsEmpty();
    void push(int elem);
    bool pop(int& elem);
    int getTop();
};

LinkStack.cpp

#include "LinkStack.h"

LinkStack::LinkStack()
{
    top = nullptr;
}

bool LinkStack::IsEmpty()
{
    return top == nullptr;
}

void LinkStack::push(int elem)
{
    try {//怕这里出问题,写了个异常。正常情况下考试 不用写异常
        LNode* s = new LNode();
        s->data = elem;
        s->next = top;
        top = s;
    }
    catch (std::bad_alloc)
    {
        cerr << "BAD_ALLOC!!!" << endl;
    }
}

bool LinkStack::pop(int& elem)
{
    bool res;
    if (IsEmpty() == true) {
        res = false;
    }
    else {
        LNode* p;
        p = top;
        top = top->next;
        elem = p->data;
        delete p;
        res = true;
    }
    return res;
}

int LinkStack::getTop()
{
    return top->data;
}

MyMath.h

#pragma once
#include"LinkStack.h"

class MyMath
{
public:
    static int calculatePostfixExpression(char* str);
};

MyMath.cpp

#include "MyMath.h"

int MyMath::calculatePostfixExpression(char* str)
{
    LinkStack s;
    int i = 0;
    int res;
    int temp[2];
    while (str[i] != '\0') {
        if (str[i] > '0' && str[i] < '9') {
            s.push(str[i] - '0');
        }
        else {
            for (int i = 0; i < 2; i++) {
                if (s.pop(temp[i]) == false) {
                    cerr << "Expression Error!!!" << endl;
                    exit(1);
                }
            }
            switch (str[i]) {
            case '+':
                s.push(temp[1] + temp[0]);
                break;
            case '-':
                s.push(temp[1] - temp[0]);
                break;
            case '*':
                s.push(temp[1] * temp[0]);
                break;
            case '/':
                s.push(temp[1] / temp[0]);
                break;
            case '^':
                s.push(temp[1] ^ temp[0]);
                break;
            case '%':
                s.push(temp[1] % temp[0]);
                break;
            default:
                cerr << "Operator Error!!!" << endl;
                exit(1);
            }

        }
        i++;
    }
    res = s.getTop();
    return res;
}

main.cpp

#include"MyMath.h"

int main() {
    cout << "Input a postfix expression:" << endl;
    char str[100];
    gets_s(str);
    cout << MyMath::calculatePostfixExpression(str) << endl;

    return  0;
}

 

$flag 上一页 下一页