使用递归的链接列表 - 意外输出

时间:2017-02-18 10:46:02

标签: c recursion linked-list

我在Internet上发现这是使用递归来反转列表并将其应用于代码块但输出仅反向打印来自main函数的最后两个Insert调用。它会跳过前三个Insert调用。为什么?我确实在这里搜索过这个问题但我没理解它们,因为我是初学者。请帮助

#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};
struct Node * head;

struct Node* Insert (struct Node* head, int data)
{
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = NULL;
    if(head == NULL)
    {
        head = temp;
        return;
    }
    struct Node* temp2 = head;
    while(temp2->next != NULL)
    {
        temp2 = temp2->next;
    }
    temp2->next = temp;
}

void reversePrint(struct Node* head)
{
    if(head == NULL)
    {
        printf("\n");
        return;
    }
    reversePrint(head->next);
    printf(" %d ", head->data);
    return;
}


int main()
{
    struct Node* head = NULL;
    head = Insert(head,2);
    head = Insert(head,7);
    head = Insert(head,3);
    head = Insert(head,1);
    head = Insert(head,4);
    reversePrint(head);
    return 0;
}

O / P:4 1

1 个答案:

答案 0 :(得分:0)

备注:

  • 不要强制转换malloc的值

  • 您宣布了两个*head并让自己感到困惑

  • 当您将头声明为全局时,无需将指针传递给函数并返回指针。这不是一个好主意,但我遵循了你的代码。

<强>代码:

#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node* next;
};

struct Node * head;

void Insert (int data)
{
    struct Node* temp = malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = NULL;
    if(head == NULL)
    {
        head = temp;
        return;
    }
    struct Node* temp2 = head;
    while(temp2->next != NULL)
    {
        temp2 = temp2->next;
    }
    temp2->next = temp;
}

void reversePrint(struct Node* head)
{
    if(head == NULL)
    {
        printf("\n");
        return;
    }
    reversePrint(head->next);
    printf(" %d ", head->data);
    return;
}
int main()
{
    Insert(2);
    Insert(7);
    Insert(3);
    Insert(1);
    Insert(4);
    reversePrint(head);
    return 0;
}

<强>输出: 4 1 3 7 2