后缀表达式的计算
- 没有考虑括号
- 从左往右依次读取,如果读到数字就入栈,如果读到符号就从栈中取出两个值进行计算。在后缀表达式的计算中先出栈的为后操作数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;
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);
return 0;
}