使用递归函数打印链表

时间:2015-11-17 13:23:40

标签: c recursion tree linked-list nodes

我可以打印我的链表:

|
|-> [ID: 3] Poetry
|   |
|   |-> [ID: 3] Notes 3
|   |   
|   |-> [ID: 2] Notes 2
|   |   
|   |-> [ID: 1] Notes 1
|   |   
|
|-> [ID: 2] Diet
|   |
|   |-> [ID: 2] Diet 2
|   |   
|   |-> [ID: 1] Diet 1
|   |   
|
|-> [ID: 1] Program

使用我写的以下功能:

void printn(NODE *handle)   //only 2 depths allowed
    {
    NODE *copy_handle = NULL; 
    NODE *depth1 = NULL;
    NODE *depth2 = NULL;

    for( copy_handle = handle ; copy_handle != NULL ; copy_handle = copy_handle->pNext  )
        {
        printf("|\n|-> [ID: %d] %s\n", copy_handle->id, copy_handle->pLabel);

        if(copy_handle->pInner != NULL )
            {
            printf("|\t|\n");
            for(depth1 = copy_handle->pInner ; depth1 != NULL ; depth1 = depth1->pNext  )
                {
                printf("|\t|-> [ID: %d] %s\n", depth1->id, depth1->pLabel);

                if(depth1->pInner != NULL )
                    {
                    printf("|\t|\t|\n");
                    for(depth2 = depth1->pInner ; depth2 != NULL ; depth2 = depth2->pNext  )
                        {
                        printf( "|\t|\t|-> [ID: %d] %s\n", depth2->id, depth2->pLabel);
                        }
                    }

                printf("|\t|\t\n");
                } 
            }
        }

    }

但是这个函数是有限的,因为我只能打印节点的子节点和该子节点的子节点,或者在我的代码中调用它时,我只能允许深度= 2。我想要做的是能够打印无限深度,所以我看了我原来的功能,我觉得用递归重新设计它是合适的。所以我开发了以下内容:

void rec_printn(NODE *handle, int tab)   //unlimited depths
    {

    printf("tab %d\n", tab); //for testing purposes
    NODE *copy_handle = handle;
    for( ; copy_handle != NULL ; copy_handle = copy_handle->pNext )
        {
        printf("%*s|-> [ID: %d] %s\n", tab, " ",  copy_handle->id, copy_handle->pLabel);   //add variable spacing 

        if(copy_handle->pInner != NULL )
            {
            tab+=5;
            rec_printn(copy_handle->pInner , tab);
            }
        else if(copy_handle->pNext == NULL )
            {
            tab-=5;
            printf("<take back the indent\n"); //for testing purposes
            }

        }
    }

我遇到的麻烦是缩进不会像我在上面的原始示例中所期望的那样回来,而是我得到以下内容:

tab 5
     |-> [ID: 3] Poetry
tab 10
          |-> [ID: 3] Notes 3
          |-> [ID: 2] Notes 2
          |-> [ID: 1] Notes 1
<take back the indent
          |-> [ID: 2] Diet
tab 15
               |-> [ID: 2] Diet 2
               |-> [ID: 1] Diet 1
<take back the indent
               |-> [ID: 1] Program
<take back the indent

问题:如果缩进不是应该的,我做错了什么?

1 个答案:

答案 0 :(得分:1)

您在每次迭代时都会向tab添加5。

不是改变tab,而是将正确的值传递给函数并让递归处理它:

if (copy_handle->pInner != NULL)
{
    rec_printn(copy_handle->pInner, tab + 5);
}
else if (copy_handle->pNext == NULL )
{
    printf("<take back the indent\n");
}

这将确保tab始终具有相同的值#34;此级别&#34;。

(也就是说,而不是思考&#34;增加缩进,然后打印下一个级别&#34;,思考&#34;打印下一级别更深的缩进&#34;,如果你理解我的意思。)