-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJosephus Circle Linked List.cpp
99 lines (99 loc) · 2.02 KB
/
Josephus Circle Linked List.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
};
void show(node *head)
{
node *current = head;
cout<<"The list is ";
cout<<current->data<<" ";
while(current->next!=head)
{
current = current->next;
cout<<current->data<<" ";
}
cout<<endl;
}
void insert(node **head, int n)
{
node *current;
current = new node;
current->data = n;
current->next = NULL;
if(*head==NULL)
{
*head = current;
current->next = *head;
}
else
{
node *temp = *head;
while(temp->next!=*head)
{
temp = temp->next;
}
temp->next = current;
current->next = *head;
}
show(*head);
}
int length(node *head)
{
node *current = head;
int count =1;
if(current==NULL)
return 0;
while(current->next!=head)
{
count++;
current = current->next;
}
return count;
}
void josephusCircle(node *head, int m)
{
node *current = head;
int k = m;
while(length(head)>1)
{
node *start = head->next;
while(start->next != head)
start = start->next;
node *prev = start;
start = head;
while(k-1)
{
prev = start;
start = start->next;
k--;
}
node *eliminate = start;
if(eliminate == head)
head = eliminate->next;
node *begin = eliminate->next;
prev->next = begin;
delete(eliminate);
head = begin;
k = m;
}
current = head;
cout<<"The last element to be executed is "<<current->data;
}
int main()
{
node *head = NULL;
int n,m;
cout<<"Enter the data to be inserted(0 to end)"<<endl;
while(cin>>n)
if(n)
insert(&head,n);
else
break;
cout<<"Enter the value of M"<<endl;
cin>>m;
josephusCircle(head,m);
return 0;
}