Tuesday, 28 November 2017

Display linklist in reverse order


     
// C program reversing the Linklist (or)
Display the Linklist in reverse order

//Procedure
    //1.Use two pointer to print the last element and delete the last element
    //2.Repeat it for 'n' times,
    // where n=length of the list.
    //That is,every time last element is printed and is deleted from the list.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

//Declaration of structure of link list
struct node
{
int data;
struct node *next;
}ptr1;


void main()
{
int x,ch,n=0,i;
struct node *ptr2,*head,*ptr1;
clrscr();
printf("\t\tCreate the list\n");
printf("\t***************************\n");

// Creaion of Linklist
head=(struct node*)malloc(sizeof(struct node));
ptr1=head;
do
{
printf("Enter the data part of the node\n ");
scanf("%d",&ptr1->data);
ptr1->next=(struct node*)malloc(sizeof(struct node));
ptr1=ptr1->next;

printf("do you want to continue(1/0)\n");
scanf("%d",&ch);
n++;
}while(ch);

// Here,'n' records the length of the list
i=0;

//display ilst in reverse order
while(i<n)
{
ptr1=head;
while(ptr1->next != NULL)
{
ptr2=ptr1;
ptr1=ptr1->next;
}
printf("%d\n",ptr2->data); //Printing the last element


ptr2->next=NULL; //Deleting the last element

i++;

}
getch();
}

Hey,guys hope you understand this program.

Any queries,suggestions and alternative way solutions are welcomed.

If you want programs for some other questions ,please comment them below.

No comments:

Post a Comment