C++ 利用棧解決運算問題

來源:互聯網
上載者:User

標籤:解決   cto   main   code   ==   stack   比較   ack   入棧   

第一步需要將中綴運算式轉為尾碼運算式。這步的轉化可以說是本題的核心。

主要的轉化手段是利用棧,有如下幾個規則:

  • 數字直接輸出
  • "("直接進棧
  • ")"將棧中元素出棧直到遇到"("
  • 其他運算子需要和棧頂元素比較優先順序,如果棧頂元素的優先順序小於等於待操作的運算子的,則需要出棧並輸出。直到棧頂元素的優先順序大於待處理元素
  • 最後需要將棧中元素清空,全部輸出
int toint(string in){    int rst;    stringstream ss;    ss<<in;    ss>>rst;    return rst;}int priority(char a){    switch(a)    {    case ‘*‘: return 2;    case ‘/‘: return 2;    case ‘+‘: return 1;    case ‘-‘: return 1;    case ‘(‘: return 3;    case ‘)‘: return 3;    }}bool isdig(char a){    if(a>=‘0‘&&a<=‘9‘) return true;    else return false;}//保證每次入棧的符號的優先順序都比當前的棧頂元素要高,若此時棧頂的優先順序比入棧元素低或者等於的話,則需要出棧//知道遇到比當前需要入棧元素優先順序高的為止void midtopost(string in,vector<string>& vec){     stack<char> s;     string rst="";     int i=0;     while(true)     {              if(i>=in.length()) break;         if(isdig(in[i]))         {             string num="";             while(isdig(in[i])) num+=in[i++];             vec.push_back(num);         }         else         {             if(s.empty()) s.push(in[i++]);             else             {                 if(in[i]==‘(‘) {s.push(in[i]);}                 else if(in[i]==‘)‘)                 {                     while(s.top()!=‘(‘)                      {                         string temp="";                         temp+=s.top();                         vec.push_back(temp);                         s.pop();                     }                     s.pop();                 }                 else                 {                     if(priority(in[i])>priority(s.top())||s.top()==‘(‘) s.push(in[i]);                     else                     {                         //判斷是否為空白必須寫在前面,符合短路原則                         while(!s.empty()&&(priority(in[i])<=priority(s.top())))                         {                             string temp="";                             temp+=s.top();                             vec.push_back(temp);                             s.pop();                         }                         s.push(in[i]);                     }                 }                 ++i;             }         }     }     //清空棧     while(!s.empty())     {         string temp="";         temp+=s.top();         vec.push_back(temp);         s.pop();     }}//尾碼運算式的計算,數字進棧,符號將棧頂兩個元素出棧,運算後進棧int calc(vector<string>& vec){    stack<int> s;    for(int i=0;i<vec.size();++i)    {        if(!vec[i].compare("*"))        {            int x=s.top();            s.pop();            int y=s.top();            s.pop();            s.push(x*y);        }        else if(!vec[i].compare("-"))        {            int x=s.top();            s.pop();            int y=s.top();            s.pop();            s.push(y-x);        }        else if(!vec[i].compare("+"))        {            int x=s.top();            s.pop();            int y=s.top();            s.pop();            s.push(x+y);        }        else if(!vec[i].compare("/"))        {            int x=s.top();            s.pop();            int y=s.top();            s.pop();            s.push(y/x);        }        else        {            s.push(toint(vec[i]));        }    }    return s.top();}int main(){     string in="9+(3-1)*3+10/2";    //string s="9 3 1 - 3 * + 10 2 / +";    vector<string> vec;    midtopost(in,vec);    cout<<calc(vec)<<endl;    return 0; }

 

C++ 利用棧解決運算問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.