【问题标题】:Reversing a linked list recursively in C在C中递归地反转链表
【发布时间】:2015-05-23 08:20:10
【问题描述】:

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

【问题讨论】:

标签: c recursion linked-list


【解决方案1】:

你需要先保存head-&gt;next,然后递归调用函数revserse

另外,你无法判断head-&gt;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);

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 2012-11-05
    • 2010-09-26
    • 2020-10-02
    • 1970-01-01
    • 2017-08-16
    • 2013-07-27
    相关资源
    最近更新 更多