数据结构表达式求值Word格式.docx
《数据结构表达式求值Word格式.docx》由会员分享,可在线阅读,更多相关《数据结构表达式求值Word格式.docx(17页珍藏版)》请在冰豆网上搜索。
top]=x;
return(TRUE);
}
intPop(Stack_char*S,char*x)//出栈
top==-1)return(FALSE);
else
*x=S->
top];
top--;
return(TRUE);
intGetTop(Stack_char*S,char*x)//取栈顶
charGetTop(Stack_charS)
charx;
GetTop(&
S,&
x);
returnx;
//建立数字栈
typedefstruct//建立
floatelem[Stack_Float];
}Stack_float;
voidInitStack(Stack_float*S)//初始化
intPush(Stack_float*S,floate)//进栈
top==Stack_Float-1)return(FALSE);
top]=e;
intPop(Stack_float*S,float*x)//出栈
intGetTop(Stack_float*S,float*x)//取栈顶
floatGetTop(Stack_floatS)
floatx;
boolIn(charch)//判断字符
if(ch=='
+'
||ch=='
-'
*'
/'
('
)'
#'
)
elsereturn(FALSE);
}
floatGetNumber(char*ch)//转化数码
return(*ch-48);
floatExecute(floata,charop,floatb)
switch(op)
case'
:
return(a+b);
break;
return(a-b);
return(a*b);
return(a/b);
default:
cout<
<
"
不能运算"
;
charCompare(charx,charch)
if(x=='
||x=='
)return('
>
'
);
elsereturn('
)return('
elsereturn('
)
='
if(ch!
floatExpEvaluation()
floatn,v,a,b;
charop;
Stack_charOPTR;
Stack_floatOVS;
InitStack(&
OPTR);
OVS);
Push(&
OPTR,'
cout<
请输入一个表达式串(以#结束)"
endl;
charch;
ch=getchar();
while(ch!
||GetTop(OPTR)!
if(!
In(ch))
n=GetNumber(&
ch);
OVS,n);
switch(Compare(GetTop(OPTR),ch))
OPTR,ch);
break;
Pop(&
OPTR,&
op);
OVS,&
b);
a);
v=Execute(a,op,b);
OVS,v);
v=GetTop(OVS);
return(v);
intmain()
ExpEvaluation()<
system("
pause"
return0;
}
完善版
voidClearStack(Stack_char*S)//清空栈
top!
=-1)S->
/*建立数字栈*/
voidClearStack(Stack_float*S)//清空栈
/*一些函数*/
chara[7]={'
'
'
};
charp[7][7]=//优先权集合
{{'
},
{'
@'
}};
boolIns(charch)//判断数字
if(ch>
=48&
&
ch<
=57)return(TRUE);
boolInc(charch)//判断字符
charCompare(charx,charch)
//charx;
//GetTop(&
inti,j,k;
for(i=0;
i<
7;
i++)
if(x==a[i])j=i;
if(ch==a[i])k=i;
returnp[j][k];
Stack_charOPTR;
Stack_floatOVS;
//InitStack(&
voidExpEvaluation()
intw=0,q=0,y=0,z=0,m=0;
floatn=0,v,a,b;
Ins(ch))
)z=1;
elseif(ch=='
){w=1;
ch=getchar();
}//记录输入负号
输入错误,请重新a"
fflush(stdin);
//清理缓存
ClearStack(&
ExpEvaluation();
exit
(1);
//else{}
if(Ins(ch))
n=n*10+GetNumber(&
q=1;
//记录输入数字
y=0;
//记录输入字符
//cout<
n值"
n<
//system("
if(Inc(ch))
if(w==1)
//cout<
z"
z<
if(q==0)
if(z==1)
+++"
GetTop(OPTR)<
z=0;
m=2;
//记录负的左括号
continue;
){w=0;
else{
输入错误,请重新b"
{cout<
w"
w<
n=-n;
w=0;
if(m==2){n=-n;
m--;
m"
m<
}}
if(q==1)
栈顶"
GetTop(OVS)<
n=0;
q=0;
if(y==1)
if(GetTop(OPTR)=='
ch=='
{w=1;
//记录左括号
c"
输入错误,请重新c"
if(y==0||z==1)
d"
o栈顶"
***"
Compare(GetTop(OPTR),ch)<
y=1;
z=0;
e"
if(op=='
b==0)
输入错误,请重新d"
if(m==1){v=-v;
m=0;
*栈顶"
括号不匹配,请重新e"
Inc(ch)&
!
输入错误,请重新f"
v<
对我有帮助