中缀表达式转后缀表达式

来源:互联网 发布:手机logo免费设计软件 编辑:程序博客网 时间:2024/05/29 07:46
很久前写的代码,复习的时候翻了出来,发现以前的比较优先级函数写错了,改了改。网上的比较优先级的函数似乎大多数都有问题。
#include<iostream>
#include<sstream>
#include<cctype>
#include<stack>
using namespace std;
stack<char> s;
bool cmp(char c1, char c2)
{
    if((c1=='+'||c1=='-')&&(c2=='+'||c2=='-'))
        return true;
 if(c1=='*'||c1=='/')
  return true;
 return false;
}

int main()
{
 string line;
 char ch;
 while(1)
    {
 getline(cin,line);
 stringstream ss(line);
 while(ss>>ch)
 {
  if(isdigit(ch)) cout<<ch;
  else
  {
   if(ch=='(') s.push(ch);
   else if(ch==')')
   {
    while(s.top()!='(')
    {
     cout<<s.top();
     s.pop();
    }
    s.pop();
   }
   else
   {
    while(!s.empty()&&cmp(s.top(),ch))
    {
      cout<<s.top();
      s.pop();
    }
    s.push(ch);
   }
  }
 }
 while(!s.empty()) {cout<<s.top();s.pop();}
 cout<<endl;
    }
 return 0;
}

原创粉丝点击