SDUT 2133 数据结构实验之栈三:后缀式求值

数据结构实验之栈三:后缀式求值

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值