數據結構實驗之棧與隊列三:後綴式求值
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
對於一個基於二元運算符的後綴表示式(基本操作數都是一位正整數),求其代表的算術表達式的值。
Input
輸入一個算術表達式的後綴式字符串,以‘#’作爲結束標誌。
Output
求該後綴式所對應的算術表達式的值,並輸出之。
Sample Input
59*684/-3*+#
Sample Output
57
Hint
基本操作數都是一位正整數!
#include <iostream>
#include <string>
#include<stdio.h>
#include<stdlib.h>
#define max 1000
using namespace std;
typedef int Elemtype;
typedef struct
{
Elemtype *top;
Elemtype *base;
}Sqstack;
void initstack(Sqstack &S)
{
S.base = (Elemtype *)malloc(max *sizeof(Elemtype));
S.top = S.base;
}
void push(Sqstack &S, Elemtype e)
{
*S.top++ = e;
}
void pop(Sqstack &S, Elemtype &e)
{
e = *--S.top;
}
int main()
{
Sqstack S;
initstack(S);
char s[1001];
scanf("%s", s);
int i = 0;
Elemtype a, b;
while(s[i]!='#')
{
if(s[i]>='0'&&s[i]<='9')
{
push(S, s[i]-'0');
}
else
{
if(s[i]=='+')
{
pop(S, a);
pop(S, b);
push(S, a+b);
}
if(s[i]=='-')
{
pop(S, a);
pop(S, b);
push(S, b-a);
}
if(s[i]=='*')
{
pop(S, a);
pop(S, b);
push(S, b*a);
}
if(s[i]=='/')
{
pop(S, a);
pop(S, b);
push(S, b/a);
}
}
i++;
}
pop(S, a);
printf("%d\n", a);
return 0;
}
/***************************************************
User name: jk160532姜興友
Result: Accepted
Take time: 0ms
Take Memory: 200KB
Submit time: 2017-10-16 12:37:38
****************************************************/