输入一行表示后缀表达式,数与数之间一定有空格隔开(可能不只一个空格),最后输入@表示输入结束。
数据保证每一步的计算结果均为不超过100000的整数。
代码:
#include<iostream>
#include<stdio.h>
#include<fstream>
#include<cstdlib>
using namespace std;
#define MAXSIZE 10000
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef struct
{
int *top;
int *base;
int stacksize;
} Sq;
Sq S1;
int InitStack(Sq &S1)
{
S1.base = new int[MAXSIZE];
if(!S1.base)
exit(OVERFLOW);
S1.top = S1.base;
S1.stacksize = MAXSIZE;
return OK;
}
int Push(Sq &S1, int g)
{
*S1.top++ = g;
return OK;
}
int Pop(Sq &S1)
{
int g;
g = *--S1.top;
return g;
}
int Input(char m[MAXSIZE])
{
int h = 0;
for(; m[h - 1] != '@'; h++)
{
m[h] = getchar();
}
m[h] = '\0';
return OK;
}
int Did(char m[MAXSIZE])
{
int h = 0;
int g = 0;
for(; m[h] != '@'; h++)
{
int k;
char j;
if(m[h] >= '0' && m[h] <= '9')
{
g = g * 10 + m[h] - '0';
}
else
if((m[h] == ' ' || m[h] == '+' || m[h] == '-' || m[h] == '/' || m[h] == '*') && m[h-1] >= '0' && m[h-1] <= '9')
{
k = g;
g = 0;
Push(S1, k);
}
if(m[h] == '+' || m[h] == '-' || m[h] == '/' || m[h] == '*')
goto area;
else
{
area: j = m[h];
switch(j)
{
case '+':
{
int c;
c = Pop(S1);
int d;
d = Pop(S1);
Push(S1, d + c);
break;
}
case '-':
{
int c;
c = Pop(S1);
int d;
d = Pop(S1);
Push(S1, d - c);
break;
}
case '*':
{
int c;
c = Pop(S1);
int d;
d = Pop(S1);
Push(S1, d * c);
break;
}
case '/':
{
int c;
c = Pop(S1);
int d;
d = Pop(S1);
Push(S1, d / c);
break;
}
default:
break;
}
}
}
return OK;
}
int main()
{
InitStack(S1);
char m[MAXSIZE];
Input(m);
Did(m);
int result = Pop(S1);
cout << result << endl;
}