本文将输入的中缀表达式转换为后缀表达式后用二叉树来存储和显示。具体的方法见代码:
#include"BinaryTree.h" #include"Binarytreenode.h" #include"structure.h" #include"optoken.h" #include<vector> #include<stack> #include<string> using namespace std; class CreTree { public: /*CreTree(){}*/ CreTree( vector<struct Ste> v ): infix( v ){} BinaryTree< Binarynode< struct Ste>,struct Ste> Create_Mid(); private: vector< struct Ste > infix; }; BinaryTree< Binarynode< struct Ste>,struct Ste> CreTree::Create_Mid() { int Num = infix.size(); int n = 0,s = 0; // stack< char > Sym; OpToken op1,op2; stack< OpToken >sym; sym.push( OpToken('$') ); stack<BinaryTree< Binarynode< struct Ste>,Ste > > symstack,treestack; BinaryTree< Binarynode<struct Ste>, struct Ste> numtree ,tree,null; BinaryTree< Binarynode<struct Ste>, struct Ste > tree1,tree2; struct Ste st1; char t1; /*********************************************** * [1].numtree是建立的临时树; * [2].赋值运算符 = 在树类中已经重载了 *【3】根据运算符的优先级来确定结点的父子关系,逻辑上和 * 中缀转化为后缀相同;不同处在于,这里是建一个树,关键是 * 构建不同子树之间的关系 ***********************************************/ cout << "建栈开始:" << endl; for( int j = 0; j < Num; j ++ ) if( infix[ j ].op != '\0')//为算符 { // cout << "算符:" << infix[ j ].op << endl; char Op = infix[ j ].op; char *str = "+-*/^$"; if( strchr( str,Op)!= NULL )//【1】为运算符+ - * / ^ { op1 = OpToken( infix[ j ].op ); while( !sym.empty() && ( (op2 = sym.top()).Getisp() >= op1.Getticp()) ) { tree1 = treestack.top(); treestack.pop(); tree2 = treestack.top(); treestack.pop(); // cout << "建算符树: " << op2.GetOp() << endl; sym.pop(); st1.op = op2.GetOp(); numtree.MakeTree( st1,tree2, tree1 );//第一个参数类型为:结构体. cout << "+-*/" << endl; treestack.push( numtree ); // cout << "入栈!" << endl; }//while sym.push( op1 ); }//【1】 else if( Op == '(') sym.push( OpToken( Op ) ); else if( Op == ')') while( !sym.empty()) { t1 = sym.top().GetOp(); sym.pop(); if( t1 == '(') break; tree1 = treestack.top(); treestack.pop(); tree2 = treestack.top(); treestack.pop(); st1.op = t1; numtree.MakeTree( st1,tree2, tree1 ); treestack.push( numtree ); } } else if( infix[j].a != 0 )//为数字时直接入栈 { // cout << "数字:" << infix[ j ].a << endl; numtree.MakeTree( infix[ j ], null, null ); // cout << "建数字树: " << endl; treestack.push( numtree ); // cout << "入栈!" << endl; } while(!sym.empty() ) { // cout << "未完!" << endl; if( sym.top().GetOp() != '$') { tree1 = treestack.top(); treestack.pop(); tree2 = treestack.top(); treestack.pop(); t1 = sym.top().GetOp(); sym.pop(); st1.op = t1; numtree.MakeTree( st1, tree2, tree1 ); treestack.push( numtree ); } else sym.pop(); } tree = treestack.top();//树的" = "运算符重载了 return tree; } 这只是其中的最为主要的部分,至于其他的细节部分日后再一一帖上。。。先看一下结果:
结果显示比较长,显示了功能比较多!呵呵。。