-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP4_LinkedList_b.c
79 lines (64 loc) · 1.89 KB
/
P4_LinkedList_b.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
#include <stdio.h>
#include <stdlib.h>
// Define a structure for a node in the circular linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode != NULL) {
newNode->data = data;
newNode->next = NULL;
}
return newNode;
}
// Function to create a circular linked list of n nodes
struct Node* createCircularLinkedList(int n) {
if (n <= 0) {
return NULL;
}
struct Node* head = createNode(1);
struct Node* current = head;
for (int i = 2; i <= n; ++i) {
current->next = createNode(i);
current = current->next;
}
// Make the linked list circular by connecting the last node to the head
current->next = head;
return head;
}
// Function to solve Josephus' problem and find the survivor
int josephus(int n, int k) {
struct Node* head = createCircularLinkedList(n);
struct Node* current = head;
struct Node* prev = NULL;
// Traverse the circular linked list until only one node remains
while (current->next != current) {
// Skip k-1 nodes
for (int i = 0; i < k - 1; ++i) {
prev = current;
current = current->next;
}
// Remove the k-th node
prev->next = current->next;
printf("Eliminated: %d\n", current->data);
free(current);
current = prev->next;
}
// Return the data of the survivor
int survivor = current->data;
free(current); // Free the last remaining node
return survivor;
}
int main() {
int n, k;
printf("Enter the number of people (n): ");
scanf("%d", &n);
printf("Enter the counting interval (k): ");
scanf("%d", &k);
int survivor = josephus(n, k);
printf("The survivor is at position %d.\n", survivor);
return 0;
}