//Write a code to solve josephus problem in linked list.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
};
main()
{
struct node *start=NULL;
int n;
void create(struct node **, int);
void josephus(struct node *);
printf("Enter the number of elements you want in your linked list :");
scanf("%d",&n);
create(&start,n);
josephus(start);
getch();
}
void create(struct node **start,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
printf("Enter the %d element :",i);
scanf("%d",&(p->data));
if(*start==NULL)
*start=p;
else
lst->next=p;
lst=p;
p->next=*start;
}
}
void josephus(struct node *start)
{
struct node *temp,*p;
int n,count;
printf("\nwhich element you want to delete in josephus problem");
scanf("%d",&n);
while(start->next!=start)
{
count=1;
p=start;
while(count<=n-2)
{
p=p->next;
count++;
}
temp=p->next;
p->next=temp->next;
free(temp);
start=p->next;
}
printf("the last item in josephus problem is %d",start->data);
}
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
};
main()
{
struct node *start=NULL;
int n;
void create(struct node **, int);
void josephus(struct node *);
printf("Enter the number of elements you want in your linked list :");
scanf("%d",&n);
create(&start,n);
josephus(start);
getch();
}
void create(struct node **start,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
printf("Enter the %d element :",i);
scanf("%d",&(p->data));
if(*start==NULL)
*start=p;
else
lst->next=p;
lst=p;
p->next=*start;
}
}
void josephus(struct node *start)
{
struct node *temp,*p;
int n,count;
printf("\nwhich element you want to delete in josephus problem");
scanf("%d",&n);
while(start->next!=start)
{
count=1;
p=start;
while(count<=n-2)
{
p=p->next;
count++;
}
temp=p->next;
p->next=temp->next;
free(temp);
start=p->next;
}
printf("the last item in josephus problem is %d",start->data);
}