我能打印我的鏈接列表清單:打印鏈接使用遞歸函數
|
|-> [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");
}
}
}
}
此功能但是在我有限的」 m只能夠打印節點的子節點和該子節點的子節點,或者在我的代碼中調用它時,我只能打印深度= 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
問題:我做錯了什麼,縮進不是他們應該的?
你總是遞增之前調用5,所以'tab- = 5'被取消。快速解決方法是做'tab- = 10;' – mtijanic