博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
猴子选大王
阅读量:6985 次
发布时间:2019-06-27

本文共 1500 字,大约阅读时间需要 5 分钟。

m只猴子围坐成一个圈,按顺时针方向从1到m编号。然后从1号猴子开始沿顺时针方向从1开始报数,报到n的猴子出局,再从刚出局猴子的下一个位置重新开始报数,如此重复,直至剩下一个猴子,它就是大王。设计并编写程序,实现如下功能:

(1)要求由用户输入开始时的猴子数m、报数的最后一个数n。
(2)给出当选猴王的初始编号。

代码实现:

#include 
#include
struct Node{ int data; struct Node *next;};int main(){ struct Node *head, *s, *q, *t; int n, m, count=0, i; printf("input the number m:"); scanf("%d",&m); printf("input the number n:"); scanf("%d",&n); //========================= //创建循环链表 for(i = 0; i< m;i++) { s = (struct Node *)malloc(sizeof(struct Node)); s->data = i+1; s->next = NULL; if(i == 0) { head = s; q = head; } else { q->next = s; q = q->next; } } q->next = head; //========================= printf("init:\r\n"); q = head; while(q->next != head) { printf("%d ",q->data); q = q->next; } printf("%d ",q->data); //========================= q = head; printf("\r\nout:\r\n"); do{ count++; if(count == n-1) { t=q->next; q->next=t->next; printf("%d ", t->data); free(t); count=0; } q = q->next; }while(q->next != q); printf("\r\nthe king is: %d\r\n",q->data); free(q);}

运行结果:

input the number m:10input the number n:3init:1 2 3 4 5 6 7 8 9 10 out:3 6 9 2 7 1 8 5 10 the king is: 4

 

转载于:https://www.cnblogs.com/swblog/p/3326176.html

你可能感兴趣的文章
iOS游戏开发教程资源
查看>>
(转)OpenSSL命令---pkcs12
查看>>
测试C#代码执行时间
查看>>
python中一个汉字点3个字节? utf-8
查看>>
JS中的正则表达式
查看>>
js判断一个对象是否为空
查看>>
android中的相对路径
查看>>
Python:通过远程监控用户输入来获取淘宝账号和密码的实验(二)
查看>>
20145209刘一阳《JAVA程序设计》第七周课堂测试
查看>>
树的遍历和代码实现
查看>>
IT兄弟连 JavaWeb教程 jQuery对AJAX的支持经典案例
查看>>
软件测试(四)之 PrintPrimes
查看>>
1011. World Cup Betting (20)
查看>>
编写一个判断素数的函数,在主函数输入一个整数时,输出是否素数的信息。...
查看>>
【JS】//将中文逗号转换为英文逗号
查看>>
Java方法 传值方式
查看>>
构造方法 练习
查看>>
PhpStorm 配置Xdebug
查看>>
stagefright omx小结
查看>>
201621123085 《Java程序设计》第2周学习总结
查看>>