Basic circular linked list in C++

A circular linked list is a list in which last node contains address of head node instead of null.When user reaches at last link after that user will be moved to first node.So in this way a circle is formed.
this is very basic program, in this program just to methods are used.Create method is used to create link list and continue to take input from user, until user enters -5.The second method display is used to display the complete circular link list to the user.


Copy the below code, paste in into your favorite editor and see how circular list works.I hope you will understand because its so easy.

#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(); 
}

Reactions

Post a Comment

0 Comments