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 }