【发布时间】:2015-05-23 08:20:10
【问题描述】:
我正在尝试编写一个程序来递归地反转单链表。我的逻辑是使用两个指针prev 和head。这两个指针用于一次链接链表中的两个节点。但我无法确定递归函数的基本情况。
这是我的代码:
#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;
}
【问题讨论】:
标签: c recursion linked-list