C program to print a linked list in reverals order.

Posted by Mangesh on August 11, 2018

program in c to print the linked list in reverse order.

Description:

In singly linked list we can traversal only in one direction i.e from head to tail. So it is difficult to print traversal linked list in reverse order, but we can to display data of linked list we can just using recursion and display data in reverse order without traversing in reverse order.

Program :

#include<stdio.h>
#include<conio.h>
typedef struct node
{
  int data;
  struct node *next,*prev;
} node;
void display(node *list)
{
  printf("\nElements in linked list : ");
  while(list != NULL)
  {
    printf("  %d",list->data);
    list = list->next;
  }
}
void displayreverse(node *list)
{

  if(list != NULL && list->next != NULL)
    displayreverse(list->next);
  printf("  %d",list->data);


}

void main()
{
  node *head, *tail;
  char character ='y';
  head = (node *) malloc (sizeof(node));
  head->prev = NULL;
  clrscr();
  tail = head;
  while(character == 'y')
  {
    printf("Enter the element value : ");
    scanf("%d",&tail->data);
    printf("Do you want to add more element : ");
    scanf("%s",&character);
    if(character=='y')
    { int temp;
      temp = tail;
      tail->next =  (node *) malloc(sizeof(node));
      tail = tail->next;
      tail->prev = temp;
    }
    else
    {
      tail->prev
      tail->next=NULL;
    }
  }
  display(head);
  printf("Element in reverse order are : ");
  displayreverse(head);

getch();
}

Output:

display linked list  in reverse order executed and tested in turbo c++ 3.2

Written with from Mangesh.

Related Post
1 C program to create singly linked list.
2 C program to display elements of linked list in reverse order.
3 C program to count number of node in linked list.
4 C program to print a linked list in reverals order.
5 C program to search an element in linked list.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.