#include <iostream>
#include<stdio.h>
using namespace std;
#define MaxSize 100
typedef char ElemType;
typedef struct SqStack {
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S) {
S.top = -1;
}
bool StackEmpty(SqStack S) {
return S.top == -1;
}
bool Push(SqStack& S, ElemType e) {
if (S.top == MaxSize-1) {
return false;
}
S.data[++S.top] = e;
return true;
}
bool Pop(SqStack& S,ElemType &e) {
if (S.top == -1) {
return false;
}
e = S.data[S.top--];
return true;
}
bool GetTop(SqStack S, ElemType& e) {
if (S.top == -1) {
return false;
}
e = S.data[S.top];
return true;
}
bool bracketCheck(char str[], int length) {
ElemType data[MaxSize];
int top = -1;
for (int i = 0; i < length; i++) {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
data[++top] = str[i];
}
else {
if (top == -1) {
return false;
}
ElemType e = data[top--];
if (!(e == '(' && str[i] == ')' || e == '[' && str[i] == ']' || e == '{' && str[i] == '}')) {
return false;
}
}
}
return top == -1;
}
char* parseToSuffixExpression(char* str) {
SqStack S;
InitStack(S);
int len = strlen(str);
char* res = (char*)malloc(sizeof(char) * len);
int k = 0;
for (int i = 0; i < len; i++) {
if (str[i] >= '0' && str[i] <= '9') {
res[k++] = str[i];
}
else if (str[i] == '(') {
Push(S, str[i]);
}
else if (str[i] == ')') {
char e;
while (!StackEmpty(S)) {
Pop(S, e);
if (e == '(') {
break;
}
res[k++] = e;
}
}
else {
if (str[i] == '+' || str[i] == '-') {
char e;
GetTop(S, e);
while (!StackEmpty(S)&&e != '(') {
Pop(S, e);
res[k++] = e;
GetTop(S, e);
}
Push(S,str[i]);
}
else if (str[i] == '*' || str[i] == '/') {
char e;
GetTop(S, e);
while (!StackEmpty(S)&&(e == '*' || e == '/')&&e!='(') {
Pop(S, e);
res[k++] = e;
GetTop(S, e);
}
Push(S, str[i]);
}
}
}
char e;
while (!StackEmpty(S)) {
Pop(S, e);
res[k++] = e;
}
res[k] = '\0';
return res;
}
int evalRPN(char* str) {
SqStack S;
InitStack(S);
int res = 0;
for (int i = 0; i < strlen(str); i++) {
if (str[i] >= '0' && str[i] <= '9') {
Push(S, str[i]);
}
else {
char num1, num2;
Pop(S, num1);
Pop(S, num2);
if (str[i] == '+') {
res = (num2 - '0') + (num1 - '0');
}
if (str[i] == '-') {
res = (num2 - '0') - (num1 - '0');
}
if (str[i] == '*') {
res = (num2 - '0') * (num1 - '0');
}
if (str[i] == '/') {
res = (num2 - '0') / (num1 - '0');
}
Push(S, res + '0');
}
}
return res;
}
int main()
{
char str[] = "1+2-3*4/(4-3*2)";
char *str1 = parseToSuffixExpression(str);
printf("%d\n", evalRPN(str1));
return 0;
}