我可以打印我的链接列表:
|
|-> [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] %sn", 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] %sn", 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] %sn", depth2->id, depth2->pLabel);
}
}
printf("|t|tn");
}
}
}
}
然而,这个函数是有限的,因为我只能打印节点的一个子节点和该子节点的一个子节点,或者当我在代码中调用它时,我只能允许深度=2。我想做的是能够无限深度地打印,所以我查看了我的原始函数,我觉得用递归重新设计它是合适的。因此,我开发了以下内容:
void rec_printn(NODE *handle, int tab) //unlimited depths
{
printf("tab %dn", tab); //for testing purposes
NODE *copy_handle = handle;
for( ; copy_handle != NULL ; copy_handle = copy_handle->pNext )
{
printf("%*s|-> [ID: %d] %sn", 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 indentn"); //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
。
不改变tab
,而是将正确的值传递给函数,并让递归处理它:
if (copy_handle->pInner != NULL)
{
rec_printn(copy_handle->pInner, tab + 5);
}
else if (copy_handle->pNext == NULL )
{
printf("<take back the indentn");
}
这将确保tab
对于"该级别"始终具有相同的值。
(也就是说,如果你明白我的意思,不要想着"增加缩进,然后打印下一个级别",而是想着"用更深的缩进打印下一级别"。)