Write a recursive function to print reverse of a Linked List

QUESTION

Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.

“TESTCASE_1”: “5\n5 4 4 3 2\n###—###SEPERATOR—###—\n2 3 4 4 5”, “TESTCASE_2”: “6 \n1 1 1 5 6 9\n###—###SEPERATOR—###—\n9 6 5 1 1 1”, “TESTCASE_3”: “4\n2 1 4 3\n###—###SEPERATOR—###—\n3 4 1 2”, “TESTCASE_4”: “7\n1 2 6 3 9 4 5\n###—###SEPERATOR—###—\n5 4 9 3 6 2 1”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

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


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


static void reverse(struct Node** head_ref)
{
    struct Node* prev   = NULL;
    struct Node* current = *head_ref;
    struct Node* next = NULL;
    while (current != NULL)
    {
        next  = current->next;  
        current->next = prev;   
        prev = current;
        current = next;
    }
    *head_ref = prev;
}

/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
            (struct Node*) malloc(sizeof(struct Node));
           
    /* put in the data  */
    new_node->data  = new_data;
               
    /* link the old list off the new node */
    new_node->next = (*head_ref);    
       
    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

/* Function to print linked list */
void printList(struct Node *head)
{
    struct Node *temp = head;
    while(temp != NULL)
    {
        printf("%d ", temp->data);    
        temp = temp->next;  
    }
}    

/* Driver program to test above function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
  int n,i;
  scanf("%d",&n);
  int arr[n];
  for(i=0;i<n;i++)
    scanf("%d",&arr[i]);
  for(i=n-1;i>=0;i--)
     push(&head, arr[i]);
     
     
     reverse(&head);                      
     
     printList(head);    
     return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro