Linked List Program in C || Reverse a Linked List
// Simple program to reverse a Linked List
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void insert(int);
void display();
void reverse();
struct node
{
int info;
node *next;
}*start=NULL;
void main()
{
for(int i=0;i<5;i++) // Only elements of array we want to reverse
{
insert(i);
}
cout<<"Elements of Linked List After Insertion\n";
display();
reverse();
cout<<"Elements of Linked List After Reverse Operation\n";
display();
getch();
}
void insert(int x)
{
node *n=(node *)malloc(sizeof(node));
n->info=x;
n->next=NULL;
if(n==NULL)
{
cout<<"Space is not vacant";
}
else if(start==NULL)
{
start=n;
}
else
{
node *ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=n;
}
}
void reverse()
{
node *ptr=start,*ptr1=NULL,*ptr2;
while(ptr!=NULL)
{
ptr2=ptr1;
ptr1=ptr;
ptr=ptr->next;
ptr1->next=ptr2;
}
start=ptr1;
}
void display()
{
node *ptr=start;
while(ptr!=NULL)
{
cout<<ptr->info;
ptr=ptr->next;
}
cout<<"\n";
}
//Output:
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment