在C中递归地反转链表

时间:2015-05-23 08:20:11

标签: c recursion linked-list

我试图写一个程序来递归反转单链表。我的逻辑是使用两个指针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

1 个答案:

答案 0 :(得分:4)

您需要先保存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);
}

然后,重置全局var head,因为你已经反转了列表,旧的head现在指向尾节点

head = reverse(NULL, head);