【问题标题】:Linked List using recursion - Unexpected Output使用递归的链表 - 意外输出
【发布时间】:2017-02-18 10:46:01
【问题描述】:

我在 Internet 上发现这个使用递归来反转列表并将其应用于代码块,但输出仅反向打印来自主函数的最后两个插入调用。它跳过前三个 Insert 调用。为什么?我确实在这里搜索过这个问题,但由于我是初学者,所以我无法理解它们。请帮忙

#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};
struct Node * head;

struct Node* Insert (struct Node* head, int data)
{
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = NULL;
    if(head == NULL)
    {
        head = temp;
        return;
    }
    struct Node* temp2 = head;
    while(temp2->next != NULL)
    {
        temp2 = temp2->next;
    }
    temp2->next = temp;
}

void reversePrint(struct Node* head)
{
    if(head == NULL)
    {
        printf("\n");
        return;
    }
    reversePrint(head->next);
    printf(" %d ", head->data);
    return;
}


int main()
{
    struct Node* head = NULL;
    head = Insert(head,2);
    head = Insert(head,7);
    head = Insert(head,3);
    head = Insert(head,1);
    head = Insert(head,4);
    reversePrint(head);
    return 0;
}

O/P : 4 1

【问题讨论】:

  • Insert 实际上并没有返回值。(你需要return head;
  • @BLUEPIXY 非常感谢 :)

标签: c recursion linked-list


【解决方案1】:

注意事项:

  • 不要强制转换 malloc 的返回值

  • 你声明了两个*head,把自己弄糊涂了

  • 当您将 head 声明为全局时,无需将指针传递给函数并返回指针。这不是一个好主意,但我遵循了你的代码。

代码:

#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};

struct Node * head;

void Insert (int data)
{
    struct Node* temp = malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = NULL;
    if(head == NULL)
    {
        head = temp;
        return;
    }
    struct Node* temp2 = head;
    while(temp2->next != NULL)
    {
        temp2 = temp2->next;
    }
    temp2->next = temp;
}

void reversePrint(struct Node* head)
{
    if(head == NULL)
    {
        printf("\n");
        return;
    }
    reversePrint(head->next);
    printf(" %d ", head->data);
    return;
}
int main()
{
    Insert(2);
    Insert(7);
    Insert(3);
    Insert(1);
    Insert(4);
    reversePrint(head);
    return 0;
}

输出: 4 1 3 7 2

【讨论】:

猜你喜欢
  • 2013-09-08
  • 1970-01-01
  • 2020-01-22
  • 2023-01-25
  • 2020-06-29
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 2017-07-11
相关资源
最近更新 更多