中序表达式转后序表达式(带括号)

来源:互联网 发布:java 线程同步机制 编辑:程序博客网 时间:2024/05/21 19:44

要求

       将中缀表达式(infix expression)转换为后缀表达式(postfix expression)。假设中缀表达式中的操作数均以单个英文字母表示,且其中只包含左括号'(',右括号‘)’和双目算术操作符+,-,*,/。


做法:

      操作数直接输出
     ( * / :直接压栈
     ) :出栈并打印栈顶元素,直到遇到'(',注意'('出栈不打印
    + - :出栈并打印栈顶元素,直到栈为空或遇到'(',将当前元素压栈
    全部遍历后,出栈并打印所有元素


#include <iostream>#include <stack>std::stack<char> s;void clearkuohao() {  while (s.top() != '(') {    std::cout << s.top();    s.pop();  }  s.pop();}void deal(char c) {  while (!s.empty() && s.top() != '(') {    std::cout << s.top();    s.pop();  }  s.push(c);}int main(){  int num;  std::cin >> num;  while (num--) {    std::string line;    std::cin >> line;    for (int i = 0; i < line.length(); ++i) {      if (line[i] == '(') {        s.push(line[i]);      } else if (line[i] == ')') {        clearkuohao();      } else if (line[i] == '*' || line[i] == '/') {        s.push(line[i]);      } else if (line[i] == '+' || line[i] == '-') {        deal(line[i]);      } else {        std::cout << line[i];      }    }    while (!s.empty()) {      std::cout << s.top();      s.pop();    }    std::cout << std::endl;  }}


0 0
原创粉丝点击