数据结构实验之栈三:后缀式求值
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
输入
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
输出
求该后缀式所对应的算术表达式的值,并输出之。
示例输入
59*684/-3*+#
示例输出
57
提示
基本操作数都是一位正整数!
后缀式本来就是方便栈操作的。。所以直接栈运算就好了,也不存在优先级问题。。。上代码:
#include <bits/stdc++.h>
using namespace std;
typedef int anytype;
struct stacks
{
struct node //链栈
{
anytype data;
struct node *next;
}*head;
stacks() //构造函数
{
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
}
bool empty() //判断空栈
{
if(head->next)
return false;
return true;
}
void push(anytype n) //入栈
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=n;
p->next=head->next;
head->next=p;
}
void pop() //出栈
{
struct node *p;
p=head->next;
if(p)
{
head->next=p->next;
free(p);
}
}
anytype top() //查询栈顶元素
{
if(!empty())
return head->next->data;
return 0;
}
};
int toCalc(int a,int b,char op) //计算函数
{
switch(op)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
default:
return 0;
}
}
int main()
{
ios::sync_with_stdio(false);
string str;
stacks s;
cin>>str;
for(int i=0;str[i]!='#';i++) //根据后缀式计算操作
{
if(isdigit(str[i]))
s.push(str[i]-48);
else
{
int b=s.top();
s.pop();
int a=s.top();
s.pop();
s.push(toCalc(a,b,str[i]));
}
}
cout<<s.top()<<endl; //最后栈顶元素即为答案
return 0;
}