您的位置:首页 > 理论基础 > 数据结构算法

数据结构--表达式计算

2017-01-24 15:37 197 查看
问题:

输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。

样例输入

1-2+3*(4-5)

样例输出

-4

思路:

中缀表达式转后缀表达式。

规则:

从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,即成为后缀表达式的一部分,若是符号,则判断其与栈顶符号的优先级,是右括号或是优先级不高于栈顶符号则栈顶元素依次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。

计算后缀表达式

从左到右遍历后缀表达式,遇到符号则运算符号前的两个数字。

代码如下:

#include <cstdio>
#include <iostream>
#define MAXSIZE 100

using namespace std;

typedef struct stack
{
int top;
char s[MAXSIZE];
} stack;
typedef struct numstack
{
int top;
int num[MAXSIZE];
} numstack;
void gettop(stack s,char *outch)
{
*outch=s.s[s.top];
}
int IntoStack(stack *st,char in)
{
if(st->top==MAXSIZE-1)return -1;
st->s[(st->top)++]=in;
return 0;
}
int OutStack(stack *st,char *out)
{
if(st->top==0)return -1;
*out=st->s[--(st->top)];
return 0;
}
int  trans(char *exp,char *cal)
{
char ch,temp;
int i=0,j=0;
ch=exp[0];
stack st;
st.top=0;
while(ch!='\0')
{
switch(ch)
{
case '(':
IntoStack(&st,ch);
break;
case '+':
case '-':
while(st.top!=0&&st.s[st.top-1]!='(')
{
OutStack(&st,&temp);
cal[j++]=temp;
}
IntoStack(&st,ch);
break;
case '*':
case '/':
while(st.top!=0&&st.s[st.top-1]!='('&&
(st.s[st.top-1]=='*'||st.s[st.top-1]=='/'))
{
OutStack(&st,&temp);
cal[j++]=temp;
}
IntoStack(&st,ch);
break;
case ')':
while
c7d9
(st.top!=0)
{
OutStack(&st,&temp);
if(temp!='(')
cal[j++]=temp;
else
break;
}
break;
case ' ':
break;
default :
while(ch>='0'&&ch<='9')
{
cal[j++]=ch;
ch=exp[++i];
}
i--;
cal[j++]='#';
break;
}
ch=exp[++i];
}
while(st.top!=0)
{
cal[j++]=st.s[--(st.top)];
}
cal[j]='\0';
return 0;
}
int calculate(char exp[])
{
int i=0,temp,a,b;
numstack numst;
numst.top=0;
while(exp[i]!='\0')
{
temp=0;
while(exp[i]>='0'&&exp[i]<='9')
{
temp=temp*10+(exp[i++]-'0');
}
if(exp[i]=='#')
{
i++;
numst.num[numst.top++]=temp;
}
else
{
b=numst.num[--(numst.top)];
a=numst.num[--(numst.top)];
switch(exp[i++])
{
case '+':
numst.num[(numst.top)++]=a+b;
break;
case '-':
numst.num[(numst.top)++]=a-b;
break;
case '*':
numst.num[(numst.top)++]=a*b;
break;
case '/':
numst.num[(numst.top)++]=a/b;
break;
}
}
}
return numst.num[--(numst.top)];
}
int main()
{
char  exp[100],cal[200];
scanf("%s",exp);

trans(exp,cal);
printf("%d\n",calculate(cal));

return 0;
}


本文部分内容来自博客。

新加了带小数的运算:

改一下数据类型和一个函数:

double calculate(char exp[])
{
int i=0;
double a,b,temp;
int point;
numstack numst;
numst.top=0;
while(exp[i]!='\0')
{
temp = 0;
point = 0;
while((exp[i]>='0'&&exp[i]<='9') || exp[i] == '.')
{
if(exp[i] == '.')
{
point = 1;
i++;
}
if(point != 0)
{
temp = temp + (exp[i++]-'0') * pow(0.1,point);
point++;
}
else
temp = temp*10+(exp[i++]-'0');
}
if(exp[i]=='#')
{
i++;
numst.num[numst.top++]=temp;
}
else
{
b=numst.num[--(numst.top)];
a=numst.num[--(numst.top)];
switch(exp[i++])
{
case '+':
numst.num[(numst.top)++]=a+b;
break;
case '-':
numst.num[(numst.top)++]=a-b;
break;
case '*':
numst.num[(numst.top)++]=a*b;
break;
case '/':
numst.num[(numst.top)++]=a/b;
break;
}
}
}
return numst.num[--(numst.top)];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: