M个人围成一圈,从第一个开始报数,第N个将被杀掉,最后剩下一个,其余人都将被杀掉。例如M=10,M=3,被杀掉的顺序是:3,6,9,2,7,1,8,5,10,4.
使用单循环链表实现
API函数和单循环链表一样
main.c
宏定义M为10,N为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(" "); 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 //缓存待删除结点的下一个结点 58 CircleLinkNode* pNext = pCurrent->next; 59 60 //根据值删除 61 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("出错! "); 80 } 81 printf(" "); 82 83 84 //释放链表内存 85 FreeSpace_CircleLinkList(clist); 86 87 88 system("pause"); 89 return 0; 90 }
运行结果: