-
Notifications
You must be signed in to change notification settings - Fork 0
/
Josephus.cpp
83 lines (52 loc) · 997 Bytes
/
Josephus.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
struct node
{
int data;
struct node *next;
};
int main()
{
node *start,*ptr;
int n,st,i;
printf("Enter the number of elements :\n");
scanf("%d",&n);
start=(struct node*)malloc(sizeof(struct node));
start->next=NULL;
ptr=start;
ptr->data=1;
for(i=2;i<=n;i++)
{
ptr->next=(struct node*)malloc(sizeof(struct node));
ptr=ptr->next;
ptr->data=i;
}
ptr->next=start;
printf("Enter the starting point :\n");
scanf("%d",&st);
printf("Enter the constraint 'n' such that every nth node is deleted :\n");
scanf("%d",&n);
ptr=start;
while(ptr->data!=st)
ptr=ptr->next;
i=0;
while(start->next!=start)
{
i++;
if(i==(n-1)&&ptr->next!=start)
{
ptr->next=ptr->next->next;
i=0;
}
else if (i==(n-1) && ptr->next==start)
{
start=start->next;
ptr->next=start;
i=0;
}
ptr=ptr->next;
}
printf("\nThe element remaining is : %d \n",ptr->data);
free(start);
}