有n人围成一圈,顺序排号。从第1个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来的第几号的那位。
标签:i++ bsp typedef head EDA main cli sig 约瑟夫
有n人围成一圈,顺序排号。从第1个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来的第几号的那位。
初始人数n
最后一人的初始编号
3
2
使用无头循环单链表即可
1 #include <stdio.h> 2 #include <stdlib.h> 3 typedef struct huan { 4 unsigned int a; 5 struct huan *pNext; 6 }HUAN; 7 HUAN *Create(int n) { 8 HUAN *pHead, *pNew = NULL; int i; 9 pHead = (HUAN*)malloc(sizeof(HUAN)); 10 pHead->a = 1; 11 pHead->pNext = NULL; 12 HUAN *cyclic = pHead; 13 for (i = 2; i <= n; i++) { 14 pNew = (HUAN*)malloc(sizeof(HUAN)); 15 pNew->a = i; 16 pNew->pNext = NULL; 17 cyclic->pNext = pNew; 18 cyclic = cyclic->pNext; 19 } 20 cyclic->pNext = pHead; 21 return pHead; 22 } 23 void Sort(HUAN *head) { 24 HUAN *pbefore, *p; 25 p = head; pbefore =NULL; 26 while (p->pNext!=p) { 27 for (int i = 1; i < 3; i++) { 28 pbefore = p; 29 p = p->pNext; 30 } 31 pbefore->pNext = p->pNext; 32 free(p); 33 p = pbefore->pNext; 34 35 } 36 printf("%d", p->a); 37 free(p); 38 39 40 } 41 42 int main() { 43 int n; HUAN *p; 44 scanf("%d", &n); 45 p = Create(n); 46 Sort(p); 47 48 }
标签:i++ bsp typedef head EDA main cli sig 约瑟夫
原文地址:https://www.cnblogs.com/mwq1024/p/10228459.html