1. First of all, let's understand what is Josephus ring problem:
Tell an interesting story: Joseph is a general of the Jewish army. During the uprising against Rome, his army was defeated. There are only 40 remaining troops. They are all people who would rather die than surrender and become traitors. A group of people voted to die, so they used a strategy to kill everyone one after another.
So Joseph suggested that: each time the other two people killed one person together, and the order of the people killed was determined by the drawing of lots. Joseph deliberately drew the last lot. When he killed the last person except him and the rest, he persuaded another person who was not dead to surrender to Rome.
Generally speaking:
Kill according to the following rules:
- Everyone in a circle
- Count clockwise. People who report to 3 every time will be killed
- Those killed will be removed from the room
- Then report again from the next person killed, continue to report 3, and then clear until the remaining one
Then the program is implemented as follows:
Definition of linked list: defined as number, so the data item is int
typedef struct NODE{ struct NODE *next; int data; }Node,*Linklist;
Because it's a loop up to the last person, all can use a special linked list: a loop linked list. When there is only one element left in the list, it is considered finished. That is, L - > next = L;
#include <stdio.h> #include <stdlib.h> #include "Linklist.h" void Print_Linklist(Linklist L) { Linklist head = L; printf("List: "); while(L->next != head) { printf("%d ",L->data); L = L->next; } printf("%d ",L->data); printf("\n"); } int main() { int i; Linklist L; Linklist head; Linklist Out; L = (Node*)malloc(sizeof(Node)); head = L; L->data = 1; L->next = head; for(i=2;i<=41;i++) { L->next=(Node*)malloc(sizeof(Node)); L->next->data = i; L->next->next = head; L = L->next; } Print_Linklist(head); L = head; while(L != L->next) { for(i=1;i<2;i++) { L = L->next; } Out = L->next; printf("%2d Number ----> Dutch act!\n",Out->data); L ->next = Out->next; L = L->next; free(Out); } printf("The survivors are:%d",L->data); return 0; }