void printLinkedList(node *head)
{
if (head == NULL)
{
printf("(empty string)");
return;
}
printf("Data: %d\n", head->data);
printLinkedList(head->next);
}
问题是,如果head不等于NULL,它会很精彩的打印链表,但是最后进入if(head == NULL)因为是递归函数,打印"(empty string )"用于任何链表(是否为空)。如果它最初是空的,我只想打印“(空字符串)”。我将如何编码?
最佳答案
您的递归函数无法知道您是第一次调用它还是在遍历列表期间调用它。所以,即使你有一个非空列表,最终你也会到达列表的末尾,在本例中它似乎是 NULL。如果您需要检查列表是否为空,我建议您编写一个辅助函数,它会为您执行此操作,然后为您启动递归,如下所示:
printHelper(node *head)
{
if (head == NULL)
{
printf("(empty string)");
}
else
{
printLinkedList(head)
}
}
然后从递归函数中取出printf("(empty string)")。
或者,如果您真的想将它保留为单个递归函数,您可以添加一个随着每次递归调用递增的计数器参数,如下所示:
void printLinkedList(node *head, int counter)
{
if (head == NULL)
{
if(counter == 0))
{
printf("(empty string)");
return;
}
}
else
{
++counter;
printf("Data: %d\n", head->data);
printLinkedList(head->next, counter);
}
}
然后当您第一次调用此函数时,将第二个参数作为 0 传递。
关于c - 需要在C中打印 "(empty string)."的递归printLinkedList函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33428147/