-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJosephus.cpp
90 lines (86 loc) · 1.28 KB
/
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<iostream>
class node{
public:
node *next;
int val;
node(int val);
};
node::node(int val)
{
this->val = val;
}
class List{
node *current , *head;
public:
List(){
current = head = NULL;
}
void add(int val);
void print();
int josephus();
};
void List::add(int val)
{
node *n = new node(val);
if(head == NULL)
{
head = n;
head->next = head;
current = head;
return;
}
current->next = n;
current = current->next;
current->next = head;
}
int List::josephus()
{
current = head;
node *del = head->next;
int val;
while(head->next != head)
{
for(int i = 1; i < 3; i++)
{
current = current->next;
del = del->next;
}
current->next = del->next;
if(del == head)
{
head = head->next;
}
val = del->val;
delete del;
current = current->next;
del = current->next;
std::cout << "( " << val << " out ) " << " ";
}
std::cout << std::endl;
return head->val;
}
void List::print()
{
current = head;
std::cout << "[ ";
do{
std::cout << current->val << " ";
current = current->next;
}while(current != head);
std::cout << "]\n";
}
int main()
{
List l;
l.add(1);
l.add(2);
l.add(3);
l.add(4);
l.add(6);
l.add(7);
l.add(8);
l.add(9);
l.add(10);
l.print();
std::cout << "The Leader is ( " << l.josephus()<< " )";
}