c ++使用指针和状态机构建递归树

时间:2012-09-14 18:49:45

标签: c++ pointers recursion tree state-machine

我有一个简单的状态机(在下面输入)。我的主要问题是我试图对我的状态机函数进行递归调用。我在输入函数时所做的是为我的树创建一个新节点,然后推送它。当我进行递归调用时,我会一遍又一遍地创建一个新节点。这可以工作,但是当把孩子添加到父母时,我有点困惑。有人可以帮助查看这个并帮助我采取我的树节点(父母我假设)并附上一个孩子吗?

TreeNodeClass* ProcessTree(TokenT token, vector <list <stateAssoc> >& vecTree, int depth)
  {
    int state = 1; //Assume this is a new record.
    bool noState = false;
    bool update = true;
    int dex = 0;
    string root, value, data, tag;
    TreeNodeClass* treeNode;

    treeNode = new TreeNodeClass; //Assume a new node per state machine visit.

    //Need 11 to break out of loop as well. 
    while(state != 10)
    {
      switch(state)
      {
    case 1: dex = 1;
        break;

    case 2: dex = 6; 
        root = yylval;
        break;

    case 3: dex = 7; 
        break;

    case 4: dex = 3;
        value = yylval;
        treeNode->CreateAttrib(root, value);
        break;

    case 5: dex = 2;
        break;

    case 6: dex = 4;
            data = yylval; 
        break;

    case 7: //Really Don't do anything. Set the tag creation at 8...
            dex = 8; 
        tag = yylval;
        if(data != "" and data != "authors")
          treeNode->CreateTag(data, tag);
        break;

    case 8: {
          //New TreeNode already grabbed. 
          //TreeNodeClass* childNode = new TreeNodeClass;
          childNode = ProcessTree(token, vecTree, depth+1);
          childNode->SetHeight(depth);
          treeNode->AddChildren(childNode);
        }
        token = TokenT(yylex()); //Get a new token to process.
        dex = 5;
        break;

    case 9: dex = 9;
        update = false;
        if(yylval != treeNode->ReturnTag())
        {
          state = 11; 
        }
        break;

    case 10: update = false;
        treeNode->SetHeight(1);
        break;

    default: cout << "Error " << endl;
        cout << state << endl;
        cin.get();
        break;

      }

      if(!noState)
    state = FindMatch(vecTree[dex], token);

      if(update)
    token = TokenT(yylex());
      else
    update = true;
    }
    return treeNode;

  }

您可以假设dex只是一个列表数组的索引,它将返回正确的状态或11(错误)。此外,您可以假设此函数至少在输入文件上被调用一次并且已经开始解析。谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

查看代码,

int state = 1;
//Code

while(state != 10) {
    switch(state) {
        case:1 dex = 1; break;   //Only case you run
        //more cases
        case 8: { //never enter here
          //New TreeNode already grabbed. 
          //TreeNodeClass* childNode = new TreeNodeClass;
          childNode = ProcessTree(token, vecTree, depth+1);
          childNode->SetHeight(depth);
          treeNode->AddChildren(childNode); //should work if assuming function is correct
        }
        //stuff
        break;
        default: break;//blah
    }
}
//blah

return treeNode;

除了事实state总是等于1,我认为没有其他原因使你的代码在案例8中失败。这假设treeNodeClass::AddChildren(TreeNodeClass*)已正确实施。没有那段代码,我可以认为这不是你的问题。是否有一些方法在切换中state不是1?