标签:turn default 情况 exp gets pre mes span 表达式计算
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; }
标签:turn default 情况 exp gets pre mes span 表达式计算
原文地址:https://www.cnblogs.com/SlowIsFast/p/12573238.html