16. The Joseph Problem

M people form a circle, start counting from the first, the Nth will be killed, the last one will be left, and the rest will be killed. For example, M=10, M=3, the order of being killed is: 3, 6, 9, 2, 7, 1, 8, 5, 10, 4.

Implemented using a single circular linked list

The API function is the same as the single circular linked list

main.c

Macro definition M is 10, N is 3

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<string.h>
 5 #include"CircleLinkList.h"
 6 
 7 #define M 10
 8 #define N 3
 9 
10 typedef struct MYNUM {
11     CircleLinkNode node;
12     int val;
13 }MyNum;
14 
15 void MyPrint(CircleLinkNode* data) {
16     MyNum* num = (MyNum*)data;
17     printf("%d  ",num->val);
18 }
19 
20 int MyCompare(CircleLinkNode* data1, CircleLinkNode* data2) {
21     MyNum* num1 = (MyNum*)data1;
22     MyNum* num2 = (MyNum*)data2;
23     if (num1->val == num2->val) {
24         return TRUE;
25     }
26     return FALSE;
27 }
28 
29 int main() {
30 
31     //创建循环链表
32     CircleLinkList* clist = Init_CircleLinkList();
33     //链表插入数据
34     MyNum num[M];
35     for (int i = 0; i < M; i++) {
36         num[i].val = i + 1;
37         Insert_CircleLinkList(clist, i, (CircleLinkNode*)&num[i]);
38     }
39 
40     //打印
41     Print_CircleLinkList(clist, MyPrint);
42     printf("\n");
43 
44 
45     int index = 1;
46     //辅助指针
47     CircleLinkNode* pCurrent = clist->head.next;
48     while (Size_CircleLinkList(clist) > 1) {
49         if (pCurrent == &(clist->head)) {
50             pCurrent = pCurrent->next;
51         }
52         if (index == N) {
53             
54             MyNum* temNum = (MyNum*)pCurrent;
55             printf("%d  ", temNum->val);
56 
57             //Cache the next node of the node to be deleted 
58              CircleLinkNode* pNext = pCurrent-> next;
 59  
60              // Delete 
61 according to the value              RemoveByValue_CircleLinkList(clist, pCurrent, MyCompare);
 62              pCurrent = pNext;
 63              if (pCurrent == &( clist-> head)) {
 64                  pCurrent = pCurrent-> next;
 65              }
 66              
67              index = 1 ;
 68          }
 69  
70          pCurrent = pCurrent-> next;
 71          index++ ;
72      }
 73  
74      if (Size_CircleLinkList(clist) == 1 ) {
 75          MyNum* tempNum=(MyNum* )Front_CircleLinkList(clist);
 76          printf( " %d   " ,tempNum-> val);
 77      }
 78      else {
 79          printf ( " Error!\n " );
 80      }
 81      printf( " \n " );
 82  
83  
84      // Free the linked list memory 
85      FreeSpace_CircleLinkList(clist);
86 
87 
88     system("pause");
89     return 0;
90 }

operation result:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324850223&siteId=291194637