|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 跑不掉 于 2024-10-25 21:57 编辑
为什么我的DEV没有运行出正确结果?
什么也没有打印出来
题目如下:
13个人围成一圈,从第一个人开始报数1,2,3。报到3的退出圈子。找出最后留在圈子中的人原来的序号。要求用链表实现。
代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #define N 13
- typedef struct People
- {
- int num;
- struct People *next;
- }people;
- int main()
- {
- //定义13个人的数据
- people arry[N];
-
- //建立环状链表
- people *head = arry;
- for (int i=0;i < N;++i)
- {
- head->num = i+1;
- head->next = &arry[i+1];
- head = head->next;
- }
- //构成环状结构
- arry[N-1].next = arry;
-
- //开始报数
- int count = N;
- //从1开始报数
- int i = 1;
- while (count>1)
- {
- //判断是否已经退出
- if(head->num ==0)
- {
- //跳过此人
- head = head->next;
- continue;
- }
-
- if (i == 3) //当前此人需要退出
- {
- printf("第%d个人退出\n",head->num);
- head->num = 0;
- count--;
- }
- //如果不需要退出,继续下一个报号
- ++i;
- head = head->next;
-
- //判断报号超过3,
- if(i>3)
- {
- i = 1;
- }
- }
-
- //找出编号不为0的人
- while (head->num ==0)
- {
- //找下一个人
- head = head->next;
- if(head->num != 0);
- {
- printf("没有退出的人为第%d\n个人",head->num);
- break;
- }
- }
-
- return 0;
- }
复制代码
本帖最后由 jackz007 于 2024-10-26 09:08 编辑
答案是 13
【代码1】:
- #include <stdio.h>
- #include <stdlib.h>
- int main(void)
- {
- typedef struct chain {
- int data ;
- struct chain * next ;
- } CHAIN , * PCHAIN ;
- PCHAIN head , p , q ;
- int c , i , k , n = 13 , r ;
- for(r = 1 , i = 0 ; i < n ; i ++) {
- if (p = (PCHAIN) malloc(sizeof(CHAIN))) {
- p -> data = i + 1 ;
- p -> next = NULL ;
- if(! i) {
- head = p ;
- p -> next = p ;
- } else {
- q -> next = p ;
- p -> next = head ;
- }
- q = p ;
- } else {
- fprintf(stderr , "malloc() failure.\n") ;
- r = 0 ;
- }
- }
- if(r) {
- for(k = n , c = 0 , p = q = head ; k > 1 ; p = q -> next) {
- c ++ ;
- if(! (c % 3)) {
- q -> next = p -> next ;
- k -- ;
- free(p) ;
- } else {
- q = p ;
- }
- }
- printf("%d\n" , p -> data) ;
- free(p) ;
- }
- }
复制代码
【代码2】:
- #include <stdio.h>
- #include <stdlib.h>
- int main(void)
- {
- typedef struct chain {
- int data ;
- struct chain * next ;
- } CHAIN , * PCHAIN ;
- PCHAIN head , p , q ;
- int c , f , i , k , n = 13 , r ;
- for(r = 1 , i = 0 ; i < n ; i ++) {
- if (p = (PCHAIN) malloc(sizeof(CHAIN))) {
- p -> data = i + 1 ;
- if(! i) {
- head = p ;
- p -> next = p ;
- } else {
- q -> next = p ;
- p -> next = head ;
- }
- q = p ;
- } else {
- fprintf(stderr , "malloc() failure.\n") ;
- r = 0 ;
- }
- }
- if(r) {
- for(k = n , c = 0 , p = head ; k > 1 ; p = p -> next) {
- if(p -> data) {
- c ++ ;
- if(! (c % 3)) {
- p -> data = 0 ;
- k -- ;
- }
- }
- }
- for(p = head ; ! p -> data ; p = p -> next) ;
- printf("%d\n" , p -> data) ;
- }
- if(head) {
- for(p = head , f = 1 ; f ; p = q) {
- if(p -> next == head) f = 0 ;
- q = p -> next ;
- free(p) ;
- }
- }
- }
复制代码
|
|