-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathquestion59.c
83 lines (64 loc) · 1.22 KB
/
question59.c
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
/*
http://practice.geeksforgeeks.org/problems/game-of-death-in-a-circle/0
*/
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *newNode(int data){
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = data;
temp->next= NULL;
return temp;
}
int chooseNum(int n, int k) {
struct node *temp = newNode(1);
struct node *head = temp;
int i;
for(i=1;i<n;i++) {
temp->next = newNode(i+1);
temp = temp->next;
}
temp->next = head; //making it circular
int remainingElem = n;
struct node *p = head;
struct node *prev = temp;
// printf("here is prev %d\n", prev->data);
struct node *help;
int counter = 1;
if(counter == k){
help = p;
p = p->next;
prev->next = p;
free(help);
counter = 1;
remainingElem--;
}
while(remainingElem > 1) {
prev = p;
p = p->next;
counter++;
if(counter == k) {
help = p;
p = p->next;
prev->next = p;
free(help);
counter = 1;
remainingElem--;
}
}
// printf("\nreturing %d\n", prev->data);
return prev->data;
}
int main() {
int cases;
scanf("%d", &cases);
int i;
for(i=0;i<cases;i++) {
int n,k;
scanf("%d %d", &n, &k);
printf("%d\n", chooseNum(n,k));
}
}