【发布时间】: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