需要打印“(空字符串)”的递归 printLinkedList 函数。在 C

Recursive printLinkedList function needing to print "(empty string)." in C

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),因为是递归函数,打印"(空字符串)”对于任何链表(空与否)。如果它最初是空的,我只想打印“(空字符串)”。我将如何编码?

您的递归函数无法知道您是第一次调用它还是在遍历列表期间调用它。所以,即使你有一个非空列表,最终你也会到达列表的末尾,在本例中它似乎是 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 传递。

void printLinkedList(node *head)
{

    if (head == NULL)
    {
        printf("(empty list)\n");
        return;
    }
    if (head->next == NULL)
    {
        printf("Data: %d\n", head->data);
        return;
    }

    printf("Data: %d\n", head->data);
    printLinkedList(head->next);
}