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 }
  • 相关阅读:
    java-transaction事件
    Cookie,Session基础知识
    JSP基础笔记
    PHP----学生管理系统
    C语言程序设计-----贪吃蛇
    2019年数维杯三场征战赛
    回忆2018年高教杯数学建模大赛
    iPad横屏模式研究
    IOS UIWebView截获html并修改便签内容,宽度自适应
    如何保持iOS上键盘出现时输入框不被覆盖
  • 原文地址:https://www.cnblogs.com/huxiaobai/p/10204411.html
Copyright © 2011-2022 走看看