gpt4 book ai didi

c - 在C中递归地反转链表

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:15 26 4
gpt4 key购买 nike

我试图编写一个程序来递归地反转单向链表。我的逻辑是使用两个指针 prevhead。这两个指针用于一次链接链表中的两个节点。但是我无法确定递归函数的基本情况。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node *next;
};

struct node *head = NULL;

void add(int n)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data = n;
temp->next = NULL;
if(head == NULL)
{
head = temp;
return;
}
temp->next = head;
head = temp;
}

void print()
{
struct node *temp = head;
putchar('\n');
printf("The List is : ");
while(temp!=NULL)
{
printf(" %d ",temp->data);
temp = temp->next;
}
}

void reverse(struct node *prev, struct node *head)
{
head->next = prev;
if(head->next == NULL)
{
/* To make the last node pointer as NULL and determine the head pointer */
return;
}
reverse(prev->next, head->next);
}


int main(void)
{
add(1);
add(2);
add(3);
add(4);
add(5);
print();
reverse(NULL, head);
print();
return 0;
}

enter image description here

最佳答案

需要先保存head->next,然后递归调用func revserse

此外,你无法判断head->next,它可能是null

struct node* reverse(struct node *prev, struct node *head)
{
if(head == NULL)
{
/* To make the last node pointer as NULL and determine the head pointer */
return prev;
}
struct node * next = head->next;
head->next = prev;
return reverse(head, next);
}

然后,重置全局变量head,因为你已经颠倒了列表,旧的head现在指向尾节点

head = reverse(NULL, head);

关于c - 在C中递归地反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410515/

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