insert into sorted circular linked list code example
Example: circular linked list insertion
#include <iostream>
using namespace std;
class node
{
public:
int data;
node*next;
};
node*head=NULL;
void insert_begin(int a)
{
node*temp=new node;
temp->data=a;
if(head==NULL)
{
temp->next=temp;
head=temp;
}
else
{
node*ptr=new node;
ptr=head;
while(ptr->next!=head)
{
ptr=ptr->next;
}
ptr->next=temp;
temp->next=head;
head=temp;
}
}
void insert_end(int a)
{
node*temp=new node;
temp->data=a;
if(head==NULL)
{
temp->next=head;
head=temp;
}
else
{
node*ptr=new node;
ptr=head;
while(ptr->next!=head)
{
ptr=ptr->next;
}
ptr->next=temp;
temp->next=head;
}
}
void printf()
{
node*temp=new node;
temp=head;
do
{
cout<<temp->data<<" ";
temp=temp->next;
}while(temp!=head);
cout<<endl;
}
int main()
{
while(1)
{
cout<<"1-insert at begin"<<endl<<"2-insert at end"<<endl<<"3-exit"<<endl;
int n;
cout<<"enter your choice:"<<endl;
cin>>n;
cout<<"enter thee value you want to insert:"<<endl;
int val;
cin>>val;
switch(n)
{
case 1:
{
cout<<"enter thee value you want to insert:"<<endl;
int val;
cin>>val;
insert_begin(val);
printf();
break;
}
case 2:
{
cout<<"enter thee value you want to insert:"<<endl;
int val;
cin>>val;
insert_end(val);
printf();
break;
}
case 3:
{
exit(0);
}
default:
{
cout<<"invalid choice :"<<endl;
}
}
}
return 0;
}