qinling072 发表于 2015-9-15 11:25:02

中缀表达式转后缀表达式,以及计算结果.

//输入的时候加不加空格都行,因为是前缀表达式.  //但是输出中应该要加空格,因为有可能几个数字是挨在一起的情况.
  
  
  //has not complete the `to_prifix`, because i do not know how to do it.
  
  #include
  #include
  #include
  #include
  using namespace std;
  
  class Compute{
  public:
  Compute(string infix_);
  int Cal();
  string Prefix() { return prefix; }
  string Postfix() { return postfix; }
  private:
  string prefix;
  string infix;
  string postfix;
  private:
  void to_postfix();
  int cal(int n1, int n2, char c);
  int compare_priory(char x, char y);
  };
  
  Compute::Compute(string infix_) : infix(infix_)
  {
  to_postfix();
  }
  
  int Compute::cal(int n1, int n2, char c)
  {
  switch (c){
  case '+': return n1 + n2;
  case '-': return n1 - n2;
  case '*': return n1 * n2;
  case '/': return n1 / n2;
  }
  }
  
  
  
  int Compute::compare_priory(char x, char y)
  {
  if (x == '*' || x == '/') return 1;
  else if ((x == '+' || x == '-') && (y == '+' || y == '-')) return 1;
  else return 0;
  }
  
  
  void Compute::to_postfix()
  {
  stack optr;
  
  int len = infix.length();
  int i;
  for (i = 0; i < len; i++){
  if (infix == ' ') {
  continue;
  } else if (isdigit(infix)){
  if (i > 0 && (!isdigit(infix))){
  postfix.push_back(' ');
  postfix.push_back(infix);
  }else
  postfix.push_back(infix);
  } else {
  if (optr.empty() || compare_priory(infix, optr.top())){
  optr.push(infix);
  }else {
  while (!optr.empty() && compare_priory(optr.top(), infix)){
  postfix.push_back(' ');
  postfix.push_back(optr.top());
  postfix.push_back(' ');
  optr.pop();
  }
  optr.push(infix);
  }
  }
  }
  while (!optr.empty()){
  postfix.push_back(' ');
  postfix.push_back(optr.top());
  postfix.push_back(' ');
  optr.pop();
  }
  if (postfix.back() == ' ') postfix.pop_back();
  }
  
  int Compute::Cal()
  {
  int len = postfix.length();
  if (len == 0) return 0;
  
  stack s;
  int i;
  int nu = 0;
  for (i = 0; i < len; i ++){
  nu = 0;
  if (postfix == ' ')
  continue;
  else if (isdigit(postfix)){
  if (i > 0 && isdigit(postfix) && !s.empty()){
  nu = s.top();
  nu = nu * 10 + postfix - '0';
  s.pop();
  s.push(nu);
  }else
  s.push(postfix - '0');
  }else{
  int n1 = s.top(); s.pop();
  int n2 = s.top(); s.pop();
  s.push(cal(n2, n1, postfix));
  }
  }
  return s.top();
  }
  
  
  
  int main()
  {
  Compute c("12 * 3 + 24 * 35 / 5 - 46");

  cout
页: [1]
查看完整版本: 中缀表达式转后缀表达式,以及计算结果.