利用链表进行报数游戏


       25 个人围成一个圈,从第1个人开始顺序报号,凡报号为3和3的倍数者退出圈子,找出最后留在圈子中的人原来的序号。
  要求:用链表实现。报到3或3的倍数的结点删除;
  提示:(1)需要将链表首尾相接形成环形;
                  (2)删除时注意头、尾结点的特殊处理;
                  (3)注意循环结束的条件;

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <malloc.h>
 4 #define  N  25
 5 
 6 typedef struct people
 7 {
 8     int num;
 9     struct people *next;
10 }Person;
11 
12 //头节点创建
13 Person *cList(void)
14 {
15     Person *head=(Person *)malloc(sizeof(Person));
16     head ->next =NULL;
17     return head;
18 }
19 
20 //尾插法创建节点
21 Person * insertList(Person *pt,int i)
22 {
23     Person *cur;
24     cur=(Person *)malloc(sizeof(Person));
25     
26     cur ->num  = i;
27 
28     pt  ->next = cur;
29     cur ->next = NULL;
30     pt = cur;
31 
32     
33     return pt;
34 }
35 
36 //打印人数
37 void print(Person * head)
38 {
39     head = head ->next;
40     while(head)
41     {
42         printf("人%d\n",head->num);
43         head = head ->next;
44     }
45 
46 }
47 
48 //游戏开始
49 void gameBegin(Person *head)
50 {
51     Person *seek=NULL;
52     int loop=2;
53 
54     while(1)
55     {
56         
57         head=head->next;//两节点前进
58         seek=head->next;
59 
60         if(loop%3==0)
61         {
62             head->next=seek->next;
63             seek      =seek->next;
64             loop++;//淘汰一人,统一序号
65         }
66 
67         loop++;//继续报数
68             
69         if(head->next==seek->next)    
70             break;
71     }
72     printf("最后剩下的是:人%d\n",head->num);
73 }
74 
75 int main()
76 {
77     //创建头节点
78     Person *head =cList();
79 
80     //插入数据
81     Person *pt = head;
82     for(int i=1;i<=N;i++)
83         pt = insertList(pt,i);
84 
85     //打印链表
86     printf("玩游戏的人是:\n");
87     print(head);
88 
89     //生成环形链表
90     pt -> next = head ->next;
91 
92 
93     //开始报数
94     gameBegin(head);
95 
96     system("pause");
97     return 0;
98 }

 

转载于:https://www.cnblogs.com/huxiaobai/p/10204411.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值