Java Android Kotlin OOP

Monday, 5 March 2018

How to create simple circular linked list in C++

Circular linked list is most commonly used data structure in most object oriented languages.Linked list is used where we have no concept about user requirements.If user requirements are fixed then arrays are bests data types to store data.But when user input is not same we use linked list to store and get data.Some times simple linked lists are not sufficient to provide best implementation.In this case we use circular linked list where every element is connected with next element and last element is connected with first element. Thus a circle is created with this type of data structure.
Below a simple program is provided that can take input continuously unless user input is -5.Each element will be stored in circular linked list.Once user entered -5, linked list will be closed and then displayed to the user.       

#include<iostream>
#include<conio.h>
using namespace std;

struct node
{
int data;
node *link;
}*head=NULL;


void create()
{
node *new1=NULL;
node *end=new1;
cout<<"Enter -5 to terminate link list:"<<endl;
while(1)
{
 int info;
cout<<"Enter data: ";
cin>>info;
if(info==-5)
break;
new1=new node;
new1->data=info;
if(head==NULL)
head=new1;
else
end->link=new1;;
end=new1;
end->link=head;


 } 
}

void display()
{
node *p=head;
cout<<"\n\nYour output is:";
while(p->link!=head)
{
cout<<"   "<<p->data;
p=p->link; 
 }
cout<<"  "<<p->data;  
}

main()
{
cout<<"\t***Simple circle link list***"<<endl; 
create();
display();
getch(); 
}

Output of program:

,