#include<stdio.h>
#include<stdlib.h>
typedef struct circular {
int val;
struct circular * next;
}
cir;
cir * create();
void disp(cir * );
cir * josephus(cir * , int);
void main() {
int ch, v, p;
cir *head;
while (1) {
printf("\n1) Create a circular linked list \n2) Display the circular linked list \n3) Josephus Problem \n4) Exit ");
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch) {
case 1: head = create();
break;
case 2: printf("\nValues in the circular linked list : ");
disp(head);
break;
case 3: 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 4: 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)
return h;
temp = (cir * ) malloc(sizeof(cir));
temp -> val = v;
if (h == NULL)
h = temp;
else
ptr -> next = temp;
ptr = temp;
temp -> next = 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 * 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;
}