reverse linked_list use recursive

·

1 min read

/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include<stdio.h>
#include<stdlib.h>

struct Node{
    int data;
    struct Node* next;
};

struct Node* head = NULL;

void Print(struct Node* p){
    if(p == NULL){
        printf("\n");
        return;
    } 

    Print(p->next);//Recursive call
    printf("%d ",p->data);
}

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

void Reverse(struct Node* p){
    if (p->next == NULL){
        head = p;
        return;
    }
    Reverse(p->next);
    p->next->next = p;
    p->next = NULL;
}


int main()
{

    head = Insert(head,1);
    head = Insert(head,2);
    head = Insert(head,3);
    head = Insert(head,4);
    head = Insert(head,5);
    Print(head);
    Reverse(head);
    Print(head);

    return 0;
}