遍历C中的已知结构

时间:2012-10-22 07:12:20

标签: c traversal

我差不多完成了其余的任务,现在只需要一个打印方法来打印输出的结构。

我想知道如何编写一个循环来遍历这样的结构:

[""][ ][ ]-->  [""][ ][/]
     |              |              
   ["A"][/][/]     [""][ ][ ]-->  [""][ ][/]     
                        |              |                 
                      ["B"][/][/]    ["C"][/][/]

这是结构:

(a (b c))

OR

[""][ ][ ]-->  [""][ ][ ]--> [""][ ][/]
     |              |             |  
   ["A"][/][/]    ["B"][/][/]   ["C"][/][/] 

这是为了:

  

(a b c)

它的代码是:

struct conscell {
char symbol;
struct conscell *first;
struct conscell *rest;

};

所以,你看到的第一个空格是符号字符,下一个是conscell指针“first”,最后一个是conscell指针“rest”。

想象一下,结构是内部构建的(到目前为止完成了分配)。

所以现在,在遍历结构之后,我应该用括号打印出适当的列表。 对于上面的例子,它将是

  

(a(b c))

我完成了方法:使用当前节点数据(符号),左节点(第一个)和右节点(其余)进行树遍历。只需找到放置括号的位置即可获得正确的输出。 现在我得到:

  

a b c

打印方法:

// List is a pointer to struct conscell 
// myList will be the pointer referring to our first conscell structure  
void printList(List myList){
List current, pre;


if (myList == NULL)
    return;

current = myList;

while (current != NULL) {

    if (current->first == NULL) {
        printf("%c", current->symbol);
        current = current->rest;
    }
    else {
        /* Find the inorder predecessor of current */
        pre = current->first;
        while (pre->rest != NULL && pre->rest != current)
            pre = pre->rest;

        /* Make current as right child of its inorder predecessor */
        if (pre->rest == NULL) {
            pre->rest = current;
            current = current->first;
        }
            /* Revert the changes made in if part to restore the original 
              tree i.e., fix the right child of predecssor */
        else {
            pre->rest = NULL;
            printf("%c ", current->symbol);
            current = current->rest;
        } /* End of if condition pre->right == NULL */
    } /* End of if condition current->left == NULL*/

} /* End of while */
}

如果有人可以帮助我,我将非常感激。

1 个答案:

答案 0 :(得分:0)

只是递归地做。

如果concsell访问第一个元素,请访问第一个first != nullptrrest成员也是如此。因为你所有的元素都具有相同的结构。

你应该只注意,如果你有很多元素,你的堆栈可能会溢出。

相关问题