Best C programming code for Josephus problem (October,2020) – Circular Linked List

#include<stdio.h>
#include<conio.h>

typedef struct circular
{
int val;
struct circular *next;
}cir;

cir *create();
void disp(cir *);
void insertafter(cir *,int);
cir *insertbefore(cir *,int);
cir *del(cir *,int);
cir *josephus(cir*,int);


void main()
{
int ch,v,p;
cir *head;

while(1)
{
printf("\n1) Create \n2) Insert after\n3) Insert before \n4) Delete \n5) Display \n6)

Josephus Problem\n7) Exit");
printf("\nEnter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: head=create();
 break;
case 2: printf("\nEnter the node value after which you want to insert the new node :

");
 scanf("%d",&p);
 insertafter(head,p);
 break;
case 3: printf("\nEnter the node value before which you want to insert the new node

:");
 scanf("%d",&p);
 head=insertbefore(head,p);
 break;
case 4: printf("\nEnter the node value you want to delete : ");
 scanf("%d",&p);
 head=del(head,p);
 break;
case 5: printf("\nValues in the circular linked list : ");
 disp(head);
 break;
case 6: printf("\nEnter the counter value for Josephus problem : ");
 scanf("%d",&p);
 head=josephus(head,p);
 printf("\nThe last node remain untouched after solving the Josephus problem :

%d",head->val);
 break;

case 7: exit(0);
default: printf("Wrong choice");
}
}
}

cir *create()
{
cir *h=NULL,*ptr,*temp;
int v;
while(1)
{
printf("Enter the value for the node (0 to exit) : ");
scanf("%d",&v);
if(v==0)
break;
temp=(cir *)malloc(sizeof(cir));
temp->val=v;
if(h==NULL)
h=temp;
else
ptr->next=temp;
ptr=temp;
temp->next=h;
}
return h;
}



void insertafter(cir *h,int p)
{
cir *temp,*ptr;
int v;
ptr=h;
printf("\n Enter the value for the new node : ");
scanf("%d",&v);
temp=(cir *)malloc(sizeof(cir));
temp->val=v;
while(ptr->val!=p && ptr->next!=h)
{
ptr=ptr->next;
}
if(ptr->next==h)
printf("Value not found");
else
{
temp->next=ptr->next;
ptr->next=temp;
}
}

cir *insertbefore(cir *h,int p)
{
cir *temp,*ptr,*pre;
int v;
ptr=h;

printf("\n Enter the value for the new node : ");
scanf("%d",&v);
temp=(cir *)malloc(sizeof(cir));
temp->val=v;
if(h->val==p)
{

while(ptr->next!=h)
{
ptr=ptr->next;
}
temp->next=h;
h=temp;
ptr->next=h;
}
else
{
while(ptr->val!=p && ptr->next!=h)
{
pre=ptr;
ptr=ptr->next;
}
if(ptr->next==h)
printf("Value not found");
else
{
temp->next=pre->next;
pre->next=temp;
}
}
return h;
}

void disp(cir *h)
{
cir *ptr;
ptr=h;
while(ptr->next!=h)
{
printf("%d,",ptr->val);
ptr=ptr->next;
}
printf("%d",ptr->val);
}

cir *del(cir *h,int p)
{
cir *ptr,*pre;
ptr=h;
if(h->val==p)
{
while(ptr->next!=h)
{
ptr=ptr->next;
}
h=h->next;
ptr->next=h;
}
else
{
while(ptr->val!=p&&ptr->next!=h)
{
pre=ptr;
ptr=ptr->next;
}
if(ptr->next!=h)
{
pre->next=ptr->next;
}
else
printf("value not found");
}
return h;
}

cir *josephus(cir *h,int p)
{
cir *ptr,*pre;
int i;
ptr=h;
while(ptr->next!=ptr)
{
i=1;
while(i<p)
{
pre=ptr;
ptr=ptr->next;
i++;
}
ptr=pre->next=ptr->next;
}
return ptr;
}

Leave a Reply