gpt4 book ai didi

c - 使用递归的链表 - 意外的输出

转载 作者:行者123 更新时间:2023-11-30 16:50:10 25 4
gpt4 key购买 nike

我在互联网上找到了使用递归反转列表并将其应用到代码块中的方法,但输出仅反向打印主函数的最后两个插入调用。它会跳过前三个 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;
}

输出:4 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

关于c - 使用递归的链表 - 意外的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42314099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com