中綴運算式轉換成尾碼運算式並求值(C++棧的應用)

來源:互聯網
上載者:User
/*
* biao.cpp
*
* Created on: 2011-11-25
* Author: allenjin
*/

#include<iostream>
#include<string.h>
using namespace std;
template<class T>
class Stack{ //自訂堆棧公式化描述
public: Stack(){Top=0;}
T top(){return a[Top];}
void pop(){Top--;}
bool isempty(){
if(Top==0)return true;
else return false;}
void push(T b)
{
Top++;
a[Top]=b;}
private:
T a[100];int Top;
};
void chpost(char inorder[],char post[],int& m)//將中綴運算式轉換為尾碼運算式,參數m跟蹤尾碼運算式長度
{
int n=strlen(inorder);//擷取中綴運算式的長度
Stack<char> czf;//定義一個char型堆棧用於存放操作符;
for(int i=0;i<n;i++)
{
if(inorder[i]>='0'&&inorder[i]<='9')//若為運算元,直接添加到尾碼運算式數組中
{
post[m]=inorder[i];
m++;
}
if(inorder[i]=='(')czf.push(inorder[i]);//若為‘(’直接壓入堆棧
if(inorder[i]=='+')//若為‘+’與棧頂比較優先順序,較低則將棧頂操作符加到數組中,在將‘+’壓棧
{
if(!czf.isempty()&&(czf.top()=='*'||czf.top()=='/'||czf.top()=='-'))
{ post[m++]=czf.top();czf.pop();czf.push(inorder[i]);}
else{czf.push(inorder[i]);}
}
if(inorder[i]=='-')//若為‘-’與棧頂比較優先順序,較低則將棧頂操作符加到數組中,將‘-’壓棧
{
if(!czf.isempty()&&(czf.top()=='*'||czf.top()=='/'))
{
post[m++]=czf.top();czf.pop();czf.push(inorder[i]);
}else{czf.push(inorder[i]);}
}
if(inorder[i]=='*'||inorder[i]=='/')czf.push(inorder[i]);//若為‘*’或‘/’直接壓棧
if(inorder[i]==')')//若遇到‘)’將棧中的操作符依次彈出直到遇到‘(’結束
{
while(czf.top()!='(')
{post[m++]=czf.top();czf.pop();}
czf.pop();//彈出‘(’
}
}
while(!czf.isempty())//將棧中剩餘元素依次彈出到尾碼運算式數組中
{post[m++]=czf.top();czf.pop();}
}
int yusuan(char post[],int n)//通過尾碼運算式求值
{
Stack<int>ss;//定義int型堆棧存放運算元及每次運算結果
int a,b,c,result;
for(int i=0;i<n;i++)
{
if(post[i]>='0'&&post[i]<='9')
{
ss.push((post[i]-'0'));//將char型轉為int型
}

if(post[i]=='-')
{
b=ss.top();ss.pop();a=ss.top();ss.pop();
c=a-b;ss.push(c);
}
if(post[i]=='+')
{
b=ss.top();ss.pop();a=ss.top();ss.pop();
c=a+b;ss.push(c);
}
if(post[i]=='*')
{
b=ss.top();ss.pop();a=ss.top();ss.pop();
c=a*b;ss.push(c);
}
if(post[i]=='/')
{
b=ss.top();ss.pop();a=ss.top();ss.pop();
c=a/b;ss.push(c);
}
}
result=ss.top();//得到最後棧頂元素
ss.pop();//清空棧
return result;
}
int main(void)
{

char in[100];char a;int i=0;
cout<<"請輸入中綴運算式(#表示結束):";
while(cin>>a)//迴圈擷取輸入直到遇到‘#’結束
{
if(a=='#')break;
in[i++]=a;
}
char po[100];int n=0;
chpost(in,po,n);
cout<<"尾碼運算式為:";
for(int j=0;j<n;j++)cout<<po[j]<<"";
cout<<endl;
cout<<"運算結果為:"<<yusuan(po,n)<<endl;
return 0;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.