//Program to implement various Operations on
Circular Linked list
#include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
struct node *next;
};
typedef struct node NODE;
void display(NODE *head)
{
if(head==NULL)
{
printf("\nEmpty list");
return;
}
printf("\n");
NODE *cur=head;
do
{
printf("%2d ->",cur->val);
cur=cur->next;
}while(cur!=head);
printf(" NULL");
}
NODE *allocate(int data)
{
NODE nn=(NODE)malloc(sizeof(NODE));
if(nn!=NULL)
{
nn->val=data;
nn->next=NULL;
}
return nn;
}
NODE * insert_beg(NODE *head,int data)
{
NODE *nn=allocate(data);
if(head==NULL)
{
nn->next=nn;
head=nn;
return head;
}
NODE *cur=head;
while(cur->next!=head)
{
cur=cur->next;
}
cur->next=nn;
nn->next=head;
head=nn;
return head;
}
NODE * insert_end(NODE *head,int data)
{
NODE *nn=allocate(data);
if(head==NULL)
{
nn->next=nn;
head=nn;
return head;
}
NODE *cur=head;
while(cur->next!=head)
{
cur=cur->next;
}
cur->next=nn;
nn->next=head;
return head;
}
NODE * insert_pos(NODE *head,int data,int pos)
{
NODE *nn=allocate(data);
NODE *cur=head,*save=NULL;
int c=1;
while(cur->next!=head && c<pos)
{
save=cur;
cur=cur->next;
c++;
}
if(c==pos)
{
if(save==NULL)
{
NODE *t=head;
while(t->next!=head)
t=t->next;
nn->next=head;
t->next=nn;
head=nn;
}
else
{
save->next=nn;
nn->next=cur;
}
}
else if(c==pos-1)
{
cur->next=nn;
nn->next=head;
}
else
{
printf("\nInvalid positon");
free(nn);
}
return head;
}
NODE *delete_beg(NODE *head)
{
if(head==NULL)
{
printf("Underflow: List is empty");
return head;
}
NODE *cur=head;
NODE *tmp=head;
while(cur->next!=head)
cur=cur->next;
if(cur==head)
head=NULL;
else{
head=head->next;
cur->next=head;
}
free(tmp);
return head;
}
NODE *delete_end(NODE *head)
{
if(head==NULL)
{
printf("Underflow: List is empty");
return head;
}
NODE *cur=head,*save=NULL;
while(cur->next!=head){
save=cur;
cur=cur->next;
}
if(cur==head)
head=NULL;
else
save->next=cur->next;
free(cur);
return head;
}
NODE *delete_pos(NODE *head,int pos)
{
if(head==NULL)
{
printf("Underflow: List is empty");
return head;
}
if(pos==1)
return delete_beg(head);
NODE *cur=head,*save=NULL;
int c=1;
while(cur->next!=head && c<pos){
save=cur;
cur=cur->next;
c++;
}
if(c==pos)
{
save->next=cur->next;
free(cur);
}
else
{
printf("invalid position");
}
return head;
}
NODE *reverse(NODE *head)
{
if(head==NULL || head->next==head)
return head;
NODE *first=head,*second=head->next;
NODE *third;
while(second!=head)
{
third=second->next;
second->next=first;
first=second;
second=third;
}
second->next=first;
head=first;
return head;
}
int main()
{
NODE *head=NULL;
head=insert_beg(head,1);
head=insert_beg(head,2);
head=insert_end(head,3);
head=insert_end(head,4);
head=insert_pos(head,8,1);
head=insert_pos(head,11,6);
display(head);
head=delete_beg(head);
head=delete_end(head);
head=delete_pos(head,2);
display(head);
head=reverse(head);
display(head);
return 0;
}