簡體   English   中英

在C中以遞歸方式反向鏈接列表

[英]Reversing a linked list recursively in C

我試圖編寫一個程序來遞歸地反向一個單鏈表。 我的邏輯是使用兩個指針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;
}

在此處輸入圖片說明

您需要先保存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現在指向了tail節點

head = reverse(NULL, head);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM