0

I found this on Internet to reverse a list using recursion and applied it in codeblocks but the output only reverse prints last two Insert call from main function. It skips the first three Insert calls. Why? I did search for this problem here but I failed to understand them as I'm a beginner. Kindly help

#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

Vector
  • 21
  • 3

1 Answers1

0

NOTES:

  • Don't cast the return of value of malloc

  • You declared two *head and confused yourself

  • No need to pass pointer to function and return pointer when you have head declared as global. Which is not a good idea but I followed your code.

Code:

#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;
}

OUTPUT: 4 1 3 7 2

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86