在C中递归地反转链表
Reversing a linked list recursively in C
我试图编写一个程序来递归地反转单个 linked 列表。我的逻辑是使用两个指针 prev
和 head
。这两个指针一次用于 link 一个 linked 列表中的两个节点。但是我无法确定递归函数的基本情况。
这是我的代码:
#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;
}
需要先保存head->next
,然后递归调用函数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);
我试图编写一个程序来递归地反转单个 linked 列表。我的逻辑是使用两个指针 prev
和 head
。这两个指针一次用于 link 一个 linked 列表中的两个节点。但是我无法确定递归函数的基本情况。
这是我的代码:
#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;
}
需要先保存head->next
,然后递归调用函数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);