数据结构实验之栈三:后缀式求值
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Example Input
59*684/-3*+#
Example Output
57
法1:
#include <stdio.h>
#include <stdlib.h>
int top=0,i,stack[1001];
int main() {
char a[1001]; scanf("%s",a);
for(i=0;a[i]!='#';i++)
{ if(a[i]>='1'&&a[i]<='9')
{
stack[++top]=a[i]-'0';
}
else if(a[i]=='+')
{ stack[top-1]=stack[top-1]+stack[top]; top--; }
else if(a[i]=='-')
{ stack[top-1]=stack[top-1]-stack[top]; top--; }
else if(a[i]=='*')
{ stack[top-1]=stack[top-1]*stack[top]; top--; }
else if(a[i]=='/')
{ stack[top-1]=stack[top-1]/stack[top]; top--; } }
printf("%d\n",stack[top]);
return 0;
}
法2:
-
#include <iostream>
-
#include <bits/stdc++.h>
-
using namespace std;
-
const int MAXN=10000+5;
-
char s[MAXN];
-
int st[MAXN];
-
int get_value(int x,int y,char s)
-
{
-
if(s=='+')return x+y;
-
if(s=='-')return x-y;
-
if(s=='*')return x*y;
-
return x/y;
-
}
-
int main()
-
{
-
int top=0;
-
scanf("%s",s);
-
int i=0;
-
while(s[i]!='#')
-
{
-
if(isdigit(s[i]))st[top++]=s[i]-'0';
-
else
-
{
-
int x=st[--top];
-
int y=st[--top];
-
st[top++]=get_value(y,x,s[i]);
-
}
-
i++;
-
}
-
printf("%d\n",st[0]);
-
return 0;
-
}