不会调...
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <map>
#include <vector>
#include <stack>
using namespace std;
/*
中缀表达式转前缀表达式
示例:
输入:a+b*(c-d)-e/f
输出:-+a*b-cd/ef
*/
class node{
public:
char ch;
node* lchild;
node* rchild;
node(){
lchild = rchild = NULL;
}
};
void init_op(map<char, int> & op){
op.clear();
op['+'] = 100;
op['-'] = 100;
op['*'] = 200;
op['/'] = 200;
op['('] = 0;
op[')'] = 0;
return;
}
bool isOperator(char c){
if(c == '+' ||c == '-'|| c == '*'|| c == '/'|| c == '(' ||c == ')')
return true;
else return false;
}
//每两个需要结合运算的表达式,以对其的运算为根结点,以左右两个表达式分别作为左孩子和右孩子
node* creatTree(string str, stack <node*> & node_Stack, stack<char> & op_Stack, map <char, int> op){
node* tmp;
for(int i=0; i<str.length(); i++){
char c = str[i];
//非操作符,则左右孩子为空,为叶结点,直接入栈
if(!isOperator(c)){
tmp = new node();
tmp->ch = c;
node_Stack.push(tmp);
}else{
if(op_Stack.empty())op_Stack.push(c);
else if(c == '('){
op_Stack.push(c);
}
//如果是右括号,向前一步步计算到左括号,将括号内形成一个结点入结点栈
else if(c == ')'){
while(op_Stack.top() != '('){
node* tmp;
tmp = new node();
tmp->ch = c;
tmp->rchild = node_Stack.top();
node_Stack.pop();
tmp->lchild = node_Stack.top();
node_Stack.pop();
node_Stack.push(tmp);
}
op_Stack.pop();//弹出左括号
}
//如果优先级高于栈顶优先级,则入符号栈
if(op[c] > op[op_Stack.top()])
op_Stack.push(c);
//如果优先级低于或等于栈顶优先级,则弹栈生成结点入栈,直到优先级高于栈顶优先级(包括左括号的情况)或者栈顶为空,最后符号入栈
else{
while(!op_Stack.empty() && op[c] <= op[op_Stack.top()]){
node* tmp;
tmp = new node();
tmp->ch = c;
tmp->rchild = node_Stack.top();
node_Stack.pop();
tmp->lchild = node_Stack.top();
node_Stack.pop();
node_Stack.push(tmp);
}
op_Stack.push(c);
}
}
}
while(!op_Stack.empty()){
node* tmp;
tmp = new node();
tmp->ch = op_Stack.top();
tmp->rchild = node_Stack.top();
node_Stack.pop();
tmp->lchild = node_Stack.top();
node_Stack.pop();
node_Stack.push(tmp);
op_Stack.pop();
}
return tmp;
}
void printPref(node* T){
if(T != NULL){
cout << T->ch;
printPref(T->lchild);
printPref(T->rchild);
delete T;
}
return;
}
int main (){
stack <node*> node_Stack;
stack <char> op_Stack;
map <char, int> op;
init_op(op);
while(1){
string str;
getline(cin, str);
node* T = creatTree(str, node_Stack, op_Stack, op);
printPref(T);
}
return 0;
}