前綴轉后綴(表達式)


問題描述:

  前綴表達式轉成后綴表達式,示例:

  * + 4 2 + 3 6 => 4 2 + 3 6 + *

 

思路(樹):

  1. 從左往右掃描串

  2. 遇到操作符則遞歸構造樹節點,當前操作符是根節點,並遞歸構造左右子節點

  3. 后序遍歷當前結果,並返回

 

代碼:

 1 #include <string>
 2 #include <sstream>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 string input_str = "* + 4.3 2 + 3.5 6.2";
 8 int ind = 0;
 9 
10 //樹結構
11 typedef struct BinaryTreeNode
12 {
13     string cur_str;
14     BinaryTreeNode *left;
15     BinaryTreeNode *right;
16     BinaryTreeNode(string _cur_str)
17     {
18         cur_str = _cur_str;
19         left = NULL;
20         right = NULL;
21     }
22 } BNode_t;
23 
24 //后序遍歷樹
25 void post_traverse(BNode_t *root, string &post_str)
26 {
27     if( root == NULL )
28         return;
29     post_traverse(root->left, post_str);
30     post_traverse(root->right, post_str);
31     if( post_str != "" )
32         post_str += " " + root->cur_str;
33     else
34         post_str = root->cur_str;
35 }
36 
37 //得到下一個
38 string get_next()
39 {
40     string next = "";
41     for(; ind < input_str.size(); ind++)
42     {
43         if( input_str[ind] != ' ' )
44             next += input_str[ind];
45         else
46             break;
47     }
48     ind++;
49     return next;
50 }
51 
52 //轉換:遞歸構造樹,並后序遍歷
53 string transform()
54 {
55     string post_str;
56     string next = get_next();
57     if( ! isdigit(next[0]) )
58     {
59         BNode_t *root = new BNode_t(next);
60         root->left = new BNode_t( transform() );
61         root->right = new BNode_t( transform() );
62         post_traverse(root, post_str);
63         delete root->left;
64         delete root->right;
65         delete root;
66         return post_str;
67     }
68     else return next;
69 }
70 
71 
72 int main()
73 {
74     cout << transform() << endl;
75     return 0;
76 }

 

 

轉載請注明引用自:

  http://www.cnblogs.com/breakthings/p/4053444.html 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM