後最運算式問題

來源:互聯網
上載者:User
C/C++ code
/*完成+,-,*,/和(),並且運算元為個位元的中綴運算式轉尾碼運算式操作。假設運算式是合法的*/string mid_to_postfix(const string &str){  string result;//儲存尾碼運算式  stack<char> s;  map<char,int> m;//儲存算符的優先順序    /*     規定優先順序越高則整數值越大,加減同層級<乘除同層級     (優先順序最高,)的優先順序不用考慮    */    //建立優先順序表    m.insert(make_pair('#',0));//在棧底放置#,其優先順序最低    m.insert(make_pair('+',1));    m.insert(make_pair('-',1));    m.insert(make_pair('*',2));    m.insert(make_pair('/',2));    m.insert(make_pair('(',3));    s.push('#');      for(size_t i=0;i!=str.size();++i)      {        if(isdigit(str[i]))//是一個數字,則立即追加入result中          result.push_back(str[i]);        else//是除數字以外的其他情況        {           if(str[i]==')')//如果此時掃描到的是右括弧,則要進行出棧工作            {              //一直出棧,直到遇見(                do                {                    result.push_back(s.top());                    s.pop();                }while(s.top()!='(');                s.pop();//將(彈出棧            }            else               if(m[str[i]]>m[s.top()])//新來的算符優先順序大於棧頂元素的優先順序                   s.push(str[i]);               else                  {                    do                     {                         if(s.top()=='(')//如果棧頂元素是(,則將運算子直接入棧即可                           break;                          result.push_back(s.top());                          s.pop();                     }while(m[s.top()]>=m[str[i]]);                    s.push(str[i]);                  }        }      }      while(s.top()!='#')//將棧中的剩餘算符加入輸出中      {          result.push_back(s.top());           s.pop();      }      return result;}

聯繫我們

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