c - 需要在C中打印 "(empty string)."的递归printLinkedList函数

标签 c recursion linked-list

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/

相关文章:

java - 尝试在java中使用递归查找字符串的反向时出现StackOverflowError

c - 为什么 BSD 在链表条目中使用双指针?

c - Makefile 重新链接错误

c - [ansi c] 将 bitifield 作为引用

具有非确定性输出的 C fork and pipe 程序

recursion - 如何递归获取 XmlProvider 的所有 XElement 子项

python - python中的递归数字三角形

c - 错误: Conflicting types for 'pow' in C

跨多个 SQL 服务器的 SQL 查询

java - LinkedList 中的删除方法返回 NullPointerException