利用链表进行报数游戏


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

 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 }
相关文章
相关标签/搜索