s.pop(e);
}
4、调试分析
调试中遇到的问题、如何解决、对设计与实现的分析讨论;
调试过程中出现了中缀表达式转换为后缀表达式转换错误的问题,原因是操作符号优先级判断判断错。
算法时空分析;O(n)
5、用户使用说明
A.按照提示输入中缀表达式
B.看到屏幕输出的后缀表达式
C.将屏幕输出的后缀表达式再次按照屏幕提示输入
D.看到屏幕输出的后缀表达式的值
6、测试结果
列出测试用输入、输出;
7、源程序
列出源程序清单:
#include
#include
usingnamespacestd;
template
classarrStack
{
private:
intmSize;//栈最多存放元素个数
inttop;//栈顶指针
T*st;//存栈元素的数组
public:
chara[100];
charb[100];
arrStack(intsizee){//创建定长顺序栈的实例
mSize=sizee;
top=-1;
st=newT[mSize];
}
arrStack(){//清空
top=-1;
}
~arrStack(){//销毁
delete[]st;
}
voidclear(){//清空
top=-1;
}
boolisEmpty(){//若栈已空返回true
if(top==-1)
returntrue;
returnfalse;
}
boolpush(constTitem)//入栈O
(1)
{
/*if(top==(mSize-1)){//若上溢
T*newst=newT[mSize*2];//扩容到2倍
for(inti=0;i<=top;i++)//复制
newst[i]=st[i];
delete[]st;//释放旧空间
st=newst;//恢复st
mSize*=2;//改写mSize
}*/
st[++top]=item;//插入item
returntrue;
}
boolpop(T&item)//出栈O
(1)
{
if(top==-1){
cout<<"空栈不能删"<returnfalse;
}
else{
item=st[top--];
returntrue;
}
}
T&gettop()//取栈顶O
(1)
{
if(top==-1){
cout<<"空栈不能读取"<}
else
returnst[top];
}
boolinput(){
charin;
inti=0;
cout<<"请您输入您要转换的前缀表达式"<cin>>in;
while(in!
='='){
a[i]=in;
cin>>in;
i++;
}
a[i]='=';
i=0;
while(a[i]!
='='){
cout<i++;
}
}
inttrans(){
inti=0,j=0;
charch,e;
ch=a[i];
while(ch!
='='){
switch(ch){
case'(':
push(ch);
break;
case'+':
case'-':
case'/':
case'*':
{
while(!
isEmpty()&&gettop()!
='('&&gettop()<=ch){
e=gettop();
b[j]=e;
pop(e);
j++;
}
push(ch);
}
break;
case')':
if(!
isEmpty()){
while(gettop()!
='('){
e=gettop();
b[j]=e;
pop(e);
j++;
}
}
pop(e);
break;
default:
if(ch>='0'<='9')
b[j++]=ch;
}
ch=a[++i];
}
while(!
isEmpty()){
e=gettop();
b[j++]=e;
pop(e);
}
intk=0;
cout<"<for(;kcout<
returnj;
}
};
boolCaculator(){//全局函数来计算后缀表达式
arrStacks(100);
intnewope,ope1,ope2,e;
charc;
cout<"<while(cin>>c,c!
='='){
switch(c){
case'+':
ope2=s.gettop();s.pop(e);ope1=s.gettop();s.pop(e);s.push(ope1+ope2);break;
case'-':
ope2=s.gettop();s.pop(e);ope1=s.gettop();s.pop(e);s.push(ope1-ope2);break;
case'*':
ope2=s.gettop();s.pop(e);ope1=s.gettop();s.pop(e);s.push(ope1*ope2);break;
case'/':
ope2=s.gettop();s.pop(e);ope1=s.gettop();s.pop(e);s.push(ope1/ope2);break;
default:
cin.putback(c);
cin>>newope;
s.push(newope);
break;
}
}
cout<"<e=s.gettop();
cout<s.pop(e);
}
main(){
inti;
arrStackm(100);
m.input();
i=m.trans();
Caculator();
}