-
Notifications
You must be signed in to change notification settings - Fork 0
/
prisoner_problem.cpp
69 lines (65 loc) · 1.06 KB
/
prisoner_problem.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
#include<iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void insert_EmptyList(Node** last,int val)
{
if(*last!=NULL)
return;
else
{
Node* newnode=new Node();
newnode->data=val;
newnode->next=newnode;
*last=newnode;
}
}
void insert_AtEnd(Node** last,int val)
{
Node* newnode=new Node();
newnode->data=val;
newnode->next=(*last)->next;
(*last)->next=newnode;
*last=newnode;
}
Node* traverse_prisoners(Node* last,int start)
{
Node* p=last->next;
do{
if(p->data==start)
break;
p=p->next;
}while(p!=last->next);
return p;
}
int traverse_sweets(Node* tmp,int sweets)
{
do{
sweets--;
if(sweets==0)
break;
tmp=tmp->next;
}while(sweets>0);
return tmp->data;
}
int main()
{
int n,m,s;
cout<<"Number of prisoners- ";
cin>>n;
cout<<"Number of sweets- ";
cin>>m;
cout<<"Start from- ";
cin>>s;
Node* last=NULL;
insert_EmptyList(&last,1);
for(int i=2;i<=n;i++)
{
insert_AtEnd(&last,i);
}
Node* tmp=traverse_prisoners(last,s);
cout<<"Prisoner to get last sweet= "<<traverse_sweets(tmp,m);
return 0;
}