Tuesday, 9 May 2017

C Program to Print a Linked List in Reverse Order

C Program  tp print the elements of a Linked List along with ouput is given below.

Example:
                   If Linked List is    12 -> 13 - > 15
                   Then output will be:   15->13->12

 Note:  Here we are printling the elements of linked list in reverse order without reversing 
             the linked list

ALGORITHM
 
FUNCTION(ROOT): 
If head=NULL:
         return
Else:
         FUNCTION(ROOT->NEXT)
         printf(root->data)

PROGRAM:
 
#include <stdio.h>
#include <stdlib.h>
struct node
{
   int data;
   struct node *next;
};
void reverse_print(struct node *root);
int main()
{
   struct node *head;

   /*Making  a  Linked List */

   head=(struct node*)malloc(sizeof(struct node));
   head->data=5;
   head->next=(struct node*)malloc(sizeof(struct node));
   head->next->data=9;
   head->next->next=(struct node*)malloc(sizeof(struct node));
   head->next->next->data=11;
   head->next->next->next=(struct node*)malloc(sizeof(struct node));
   head->next->next->next->data=14;
   head->next->next->next->next=NULL;

   printf("\nThe element of Linked List in reverse order are: \n\n");
   reverse_print(head);
   printf("\n");
   return 0;
}
void reverse_print(struct node *head)
{
   if(head==NULL)
   {
       return;
   }
   else
   {
       reverse_print(head->next);
       printf("%d -> ",head->data);
   }
}


OUTPUT:

 


EmoticonEmoticon