zoukankan      html  css  js  c++  java
  • 利用链表进行报数游戏


           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
    ",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
    ",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("玩游戏的人是:
    ");
    87     print(head);
    88 
    89     //生成环形链表
    90     pt -> next = head ->next;
    91 
    92 
    93     //开始报数
    94     gameBegin(head);
    95 
    96     system("pause");
    97     return 0;
    98 }
  • 相关阅读:
    hibernate&查询
    hibernate&一对多&多对多
    hibernate&三种状态的对象&一级缓存&快照机制
    Hibernate5.0安装&基本配置&基本使用
    python获取命令行输入的参数
    node.js + express搭建服务流程
    xpath获取两个标签之间的所有标签
    flask快速入门
    03.调用js执行代码
    02.5 js中的语法知识补充
  • 原文地址:https://www.cnblogs.com/huxiaobai/p/10204411.html
Copyright © 2011-2022 走看看