用C++模拟栈来实现逆波兰表达式求解算式~
/*************************************************************************
> File Name: p.cpp
> Author: Zcy
> Mail: 296763002@qq.com
> Created Time: 三 1/23 18:16:17 2019
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
template <typename type> class S{
private:
type *val;
int head;
public:
void push(type val) {
this -> head ++;
this -> val[this -> head] = val;
}
void pop() {
this -> head --;
}
bool empty() {
return this -> head < 0;
}
type top() {
return this -> val[this -> head];
}
bool bj(char c) {
if ((c == '+' || c == '-') && (top() == '*' || top() == '/')) {
return true;
} else if ((c == '+' || c == '-') && (top() == '+' || top() == '-')){
return true;
} else if ((c == '*' || c == '/') && (top() == '*' || top() == '/')){
return true;
} else {
return false;
}
}
void init() {
this -> val = (type *)malloc(sizeof(type) * 25);
this -> head = -1;
}
void clear() {
free(this -> val);
free(this);
}
};
int jsx(char c, int a, int b) {
switch(c) {
case '*':
return a * b;
break;
case '/':
return a / b;
break;
case '+':
return a + b;
break;
default:
return a - b;
}
}
void js(S<int> *num, S<char> *ch) {
int b = num -> top();
num -> pop();
int a = num -> top();
num -> pop();
num -> push(jsx(ch -> top(), a, b));
ch -> pop();
}
int main () {
char *buffer = (char *)malloc(sizeof(char) * 25);
scanf("%s", buffer);
int val = 0;
S<int> *num = (S<int> *)malloc(sizeof(S <int>));
S<char> *ch = (S<char> *)malloc(sizeof(S <char>));
num -> init();
ch -> init();
for (int i = 0; buffer[i]; i++) {
if (isdigit(buffer[i])) {
val = val * 10 + buffer[i] - '0';
} else {
num -> push(val);
val = 0;
while(!ch -> empty() && ch -> bj(buffer[i])) {
js(num, ch);
}
ch -> push(buffer[i]);
}
}
num -> push(val);
while(!ch -> empty()) {
js(num, ch);
}
printf("%d\n", num -> top());
free(buffer);
num -> clear();
ch -> clear();
return 0;
}
如果有写的不对或者不全面的地方 可通过主页的联系方式进行指正,谢谢