后缀表达式的计算

后缀表达式的计算

  • 没有考虑括号
  • 从左往右依次读取,如果读到数字就入栈,如果读到符号就从栈中取出两个值进行计算。在后缀表达式的计算中先出栈的为后操作数b,先出栈的为前操作数a。还要注意判断除数为零的情况。
  • 判断数组读到末尾 exp[i]!='\0' 注意斜杠的方向
  • 下面是书本上的代码,使用顺序表写的
#include <iostream>
#define maxSize 100
using namespace std;
int op(int a,char Op,int b)
{
	if(Op=='+') return a+b;
	if(Op=='-') return a-b;
	if(Op=='*') return a*b;
	if(Op=='/')
	{
		if(b==0)
		{
			cout << "ERROR" << endl;
		}
		else
		{
			return a/b;
		}
	}
}
int com(char exp[])
{
	int i,a,b,c;
	int stack[maxSize];
	int top=-1;
	char Op;
	for(i=0;exp[i]!='\0';++i)
	{
		if(exp[i]>='0'&&exp[i]<='9')
		{
			stack[++top]=exp[i]-'0';
		}
		else
		{
			Op=exp[i];

			b=stack[top--];
			a=stack[top--];
			c=op(a,Op,b);
			stack[++top]=c;

		}
	}
	return stack[top];
}
int main()
{
	char a[]="2312+*+";
	cout << com(a) << endl;//答案应该为11 
	return 0;
}
  • 原本感觉用链栈会更清晰,结果写出来后发现顺序栈代码量感觉更少,下面是自己用链栈的解法
#include <iostream>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
typedef struct Node
{
	char data;
	struct Node *next;
}Node;
void push(Node *lst,char x)
{
	Node *p;
	p=(Node *)malloc(sizeof(Node));
	p->data=x;
	
	p->next=lst->next;
	lst->next=p;
}
int pop(Node *lst,char &x)
{
	if(lst->next==NULL)
		return 0;
	Node *p;
	p=lst->next;
	x=p->data;
	lst->next=p->next;
	free(p);
	return 1;
}
void cal(char *str,int l)
{
	Node *head;
	head=(Node *)malloc(sizeof(Node));
	head->next=NULL;
	Node *p=head;
	char a,b;
	for(int i=0;i<l;i++)
	{
		if(isdigit(str[i]))
		{
			push(p,str[i]);
		}
		if(ispunct(str[i]))
		{
			pop(p,b);
			pop(p,a);  //首先出栈的是第二操作数 
			if(str[i]=='+')
			{
				push(p,a+b-'0');
			}else if(str[i]=='-')
			{
				push(p,a-b+'0');
			}else if(str[i]=='*')
			{
				push(p,(a-'0')*(b-'0')+'0');
			}else if(str[i]=='/')
			{
				if(b-'0'==0)
				{
					cout << "ERROR" << endl;
					return;
				}
				else
				{
					push(p,(a-'0')/(b-'0')+'0');
				}
			}
		}
	}
	char f;
	pop(p,f);
	cout << f-'0' << endl;
}
int main()
{
	cal("2312+*+",7);//答案应该为11 
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值