//#define?MaxLen?100//存儲空間
int?tran(char?str[],?char?expr[])//將中綴表達式轉換成後綴表達式if(tran(str,expr)==0)//原來表達式,後綴表達式
{
int?st[100];//轉化過程使用的過度棧 char?ch; int?i=0,exindex=0,stindex=-1;?//i是str下標,exindex是expr下標,stindex是st下標 while((ch=str[i++])!='\0') { if(ch>='0'?&&?ch<='9')//判斷是數字 {expr[exindex]=ch;//壓棧
exindex++;//棧頂指針上移
while((ch=str[i++])!='\0'?&&?ch>='0'?&&?ch<='9')//其它位依次入棧
{
expr[exindex]=ch;
exindex++;
}
i--;//str原算術表達式棧向下遍歷
expr[exindex]='#';//以特殊字符“#”表示結束
exindex++;
} else?if(ch=='(')//判斷為左括號 {stindex++;
st[stindex]=ch;
} else?if(ch==')')//判斷為右括號 {while?(st[stindex]!='(')?
{
expr[exindex]=st[stindex];
stindex--;//依次彈出
exindex++;
}
stindex--;//'('出棧
} else?if(ch=='+'?||?ch=='-')//判斷為加減號 {while(stindex>=0?&&?st[stindex]!='(')
{
expr[exindex]=st[stindex];
stindex--;
exindex++;
}
stindex++;
st[stindex]=ch;
} else?if?(ch=='*'?||?ch=='/')//判斷為乘除號 {while(st[stindex]=='*'?||?st[stindex]=='/')
{
expr[exindex]=st[stindex];
stindex--;
exindex++;
}
stindex++;
st[stindex]=ch;?
} } while?(stindex>=0)//將棧中所有運算符依次彈出存入expr棧中 { expr[exindex]=st[stindex]; exindex++; stindex--; } expr[exindex]='\0'; return?1;}
int?compvalue(char?expr[],int?*n)?
{
int?st[100],d;//st為數棧 char?ch; int?exindex=0,stindex=-1;?//exindex是expr下標,stindex是st的下標 while((ch=expr[exindex++])!='\0') { if(ch>='0'&&ch<='9')//將數字字符轉換成數字 {d=0;
do?
{
d=10*d+ch-'0';
}?
while((ch=expr[exindex++])!='#');
stindex++;
st[stindex]=d;//數字進棧
} else//運算符操作 {switch(ch)
{
case'+':st[stindex-1]=st[stindex-1]+st[stindex];
break;
case'-':st[stindex-1]=st[stindex-1]-st[stindex];
break;
case'*':st[stindex-1]=st[stindex-1]*st[stindex];
break;
case'/':
if(st[stindex]!=0)
{?st[stindex-1]=st[stindex-1]/st[stindex];?}
else?return?0;?//除0錯誤!
break;
}
stindex--;
} } (*n)=st[stindex]; return?1;}
void?main()
{
char?str[100];//存儲原來算術表達式 char?expr[100];//存儲轉換成的後綴表達式 int?n; cout<<"輸入算術表達式:"<<endl; cin>>str; if(tran(str,expr)==0) { cout<<"原算術表達式不正確!"<<endl; } else { cout<<"轉換成後綴表達式輸出:"<<endl<<expr<<endl; if(compvalue(expr,&n)==1) {cout<<"表達式求值:"<<endl<<n<<endl;
} else {cout<<"計算錯誤!"<<endl;
} }