This C program uses a linked list to solve the Josephus problem. It creates a circular linked list of input numbers, displays the list, takes user input for the number of places to skip, and calls the survivor function. The survivor function iterates through the linked list, removing nodes at the specified interval until one node remains, which is returned as the survivor.
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
60 views
Josephus Problem Using Linked List
This C program uses a linked list to solve the Josephus problem. It creates a circular linked list of input numbers, displays the list, takes user input for the number of places to skip, and calls the survivor function. The survivor function iterates through the linked list, removing nodes at the specified interval until one node remains, which is returned as the survivor.
int main() { struct node *head = NULL; int survive, skip;
create(&head); printf("The persons in circular list are:\n"); display(head); printf("Enter the number of persons to be skipped: "); scanf("%d", &skip); survive = survivor(&head, skip); printf("The person to survive is : %d\n", survive); free(head);
return 0; }
int survivor(struct node **head, int k) { struct node *p, *q; int i;
q = p = *head; while (p->next != p) { for (i = 0; i < k - 1; i++) { q = p; p = p->next; } q->next = p->next; printf("%d has been killed.\n", p->num); free(p); p = q->next; } *head = p;
return (p->num); }
void create (struct node **head) { struct node *temp, *rear; int a, ch;
do { printf("Enter a number: "); scanf("%d", &a); temp = (struct node *)malloc(sizeof(struct node)); temp->num = a; temp->next = NULL; if (*head == NULL) { *head = temp; } else { rear->next = temp; } rear = temp; printf("Do you want to add a number [1/0]? "); scanf("%d", &ch); } while (ch != 0); rear->next = *head; }