一个旅行社要从n个旅客中选出一名旅客,为他提供免费的环球旅行服务。旅行社安排这些旅客围成一个圆圈,从帽子中取出一张纸条,用上面写的正整数m(<n)作为报数值。游戏进行时,从第一个人开始按顺时针方向自1开始顺序报数,报到m时停止报数,报m的人被淘汰出列,然后从他顺时针方向上的下一个人开始重新报数,如此下去,直到圆圈中只剩下一个人,这个最后的幸存者就是游戏的胜利者,将得到免费旅行的奖励。
代码如下:
代码
1
typedef
struct
_node
2 {
3 int number;
4 _node * pNext;
5 }node;
6
7 node * pHead = NULL;
8 node * pTear = NULL;
9 #define N 8
10 #define M 3
11 int main() {
12 node * pNode = NULL;
13 for ( int i = 1 ; i <= N ; ++ i)
14 {
15 pNode = (node * )malloc( sizeof (_node));
16 pNode -> number = i;
17 pNode -> pNext = NULL;
18 if (i == 1 )
19 {
20 pHead = pNode;
21 pTear = pNode;
22 pTear -> pNext = pHead;
23 }
24 else
25 {
26 pTear -> pNext = pNode;
27 pTear = pNode;
28 pTear -> pNext = pHead;
29 }
30 }
31
32 node * pPre = pTear;
33 node * pNext = pHead;
34 int sum = 0 ;
35 pHead = NULL;
36 pTear = NULL;
37 while (pPre -> pNext != pPre)
38 {
39 pNext = pPre -> pNext;
40 ++ sum;
41 if (sum == M)
42 {
43 if (pHead == NULL)
44 {
45 pHead = pPre -> pNext;
46 pTear = pPre -> pNext;
47 }
48 else
49 {
50 pTear -> pNext = pPre -> pNext;
51 pTear = pPre -> pNext;
52 }
53 pPre -> pNext = pNext -> pNext;
54 sum = 0 ;
55 continue ;
56 }
57 pPre = pPre -> pNext;
58 }
59 pTear -> pNext = NULL;
60 printf( " %d\n " ,pPre -> number);
61 node * p = pHead;
62 while (p != NULL)
63 {
64 printf( " %d\n " ,p -> number);
65 p = p -> pNext;
66 }
67 return 0 ;
68 }
2 {
3 int number;
4 _node * pNext;
5 }node;
6
7 node * pHead = NULL;
8 node * pTear = NULL;
9 #define N 8
10 #define M 3
11 int main() {
12 node * pNode = NULL;
13 for ( int i = 1 ; i <= N ; ++ i)
14 {
15 pNode = (node * )malloc( sizeof (_node));
16 pNode -> number = i;
17 pNode -> pNext = NULL;
18 if (i == 1 )
19 {
20 pHead = pNode;
21 pTear = pNode;
22 pTear -> pNext = pHead;
23 }
24 else
25 {
26 pTear -> pNext = pNode;
27 pTear = pNode;
28 pTear -> pNext = pHead;
29 }
30 }
31
32 node * pPre = pTear;
33 node * pNext = pHead;
34 int sum = 0 ;
35 pHead = NULL;
36 pTear = NULL;
37 while (pPre -> pNext != pPre)
38 {
39 pNext = pPre -> pNext;
40 ++ sum;
41 if (sum == M)
42 {
43 if (pHead == NULL)
44 {
45 pHead = pPre -> pNext;
46 pTear = pPre -> pNext;
47 }
48 else
49 {
50 pTear -> pNext = pPre -> pNext;
51 pTear = pPre -> pNext;
52 }
53 pPre -> pNext = pNext -> pNext;
54 sum = 0 ;
55 continue ;
56 }
57 pPre = pPre -> pNext;
58 }
59 pTear -> pNext = NULL;
60 printf( " %d\n " ,pPre -> number);
61 node * p = pHead;
62 while (p != NULL)
63 {
64 printf( " %d\n " ,p -> number);
65 p = p -> pNext;
66 }
67 return 0 ;
68 }