问题
设编号1 ,2 ,3.。。。n 的n个人围坐一圈,约定编号为K(1<=k<=n)的人 从1开始报数,数到m的那个人出列,他的下一位又从1开始报数 ,数到m的那个人出列,直到所有人都出列。
思路
首先构建一个单向环形链表,并且能够显示这个环形链表,
- 创建一个节点 这个节点 也形成一个环状 创建一个first指针 指向第一个数据,
- 在设置一个节点 curBoy (辅助指针),当创建第二个节点的时候 ,先让curBoy的next 指向第二个节点 ,然后将curboy移到第二个节点上去,第二个节点的 next 指向第一个节点 ,形成闭环。
第二部步 根据用户的输入 生成一个小孩的出圈顺序
- 需要创建一个复制指针(helper),事先让helper指向环形链表的最后一个节点。
- 在小孩报数之前 先让first 和helper 移动K-1次;移到指定的开始位置;
- 当小孩开始报数,让first和helper指针同时的移动m-1次 (m为报的数)
- 这时 可以将first指针指向的小孩出圈,
- first = first.next
- helper.next = first
- 原来的first指向的节点 就会因为没有任何的引用 会被垃圾回收掉
代码实现过程
//创建一个Boy类 表示一个节点
class Boy{
public int no;
public Boy next;
//构造器
public Boy(int no){
this.no = no;
}
}
//创建一个环形的单向链表
class CircleSingleLinkedList{
//创建第一个节点 当前没有编号
private Boy first = new Boy(-1);
//添加小孩节点 构成一个环形的链表
public void addBoy(int nums){
//对nums做一个校验
if(nums<1){
System.out.println("nums值不正确");
return;
}
Boy curBoy =null;//辅助指针 帮助构建环形链表
//使用for来创建环形链表
for(int i = 1; i<=nums;i++){
//根据编号 创建小孩节点
Boy boy = new Boy(i);
//如果是第一个小孩
if (i ==1){
first = boy;
first.next =first;//构建一个环
curBoy = first;//让curboy 指向第一个小孩
}else {
curBoy.next=boy;//当前链接指向下一个boy
boy.next=first;//boy的下一个点 指向第一个点
curBoy=boy;//当前小孩 下移一个位置
}
}
}
//遍历当前环形链表
public void showBoy(){
//判断链表是否为空
if(first == null){
System.out.println("没有小孩");
return;
}
//因为first不能动 所以 我们仍然使用一个辅助指针完成遍历
Boy curBoy = first;
while (true){
System.out.printf("小孩的编号%d \n",curBoy.no);
if (curBoy.next == first){
break;
}
curBoy = curBoy.next;
}
}
//根据用户的输入 计算出小孩出圈的顺讯
/**
*
* @param starNo 表示从第几个小孩开始数数
* @param countNum 表示数几下
* @param nums 表示最初有多少个小孩在去圈中
*/
public void countBoy(int starNo,int countNum,int nums){
//先对数据进行校验
if (first == null || starNo < 1 || starNo >nums){
System.out.println("参数输入有误 请重新输入");
return;
}
//创建一个辅助指针helper 帮助小孩出圈
Boy helper =first;
// 需要创建一个辅助指针(变量)helper 事先应该指向环形链表的最后这个节点
while (true){
if (helper.next == first){//说明help指向最后一个小孩子
break;
}
helper=helper.next;
}
//报数前 要将first与helper定位
for (int j = 0 ;j < starNo - 1;j++){
first = first.next;
helper =helper.next;
}
//当小孩报数时 让first 和helper 指针同时的移动m-1次,然后出圈;
//这里是一个循环操作,直到圈中仅有一个节点
while (true){
if (helper == first){// = 的时候 说明只有一个人
break;
}
//让first 和helper 指针同时移动countNum-1
for (int j = 0;j < countNum - 1;j++){
first = first.next;
helper =helper.next;
}
//这是first指向的节点 就是要出圈的小孩节店
System.out.printf("小孩%d出圈 \n",first.no);
//将小孩出圈
first = first.next;
helper.next =first;
}
System.out.printf("最后留在圈中小孩为%d \n",first.no);
}
}
测试
public class Josepfu {
public static void main (String[] args){
//构建
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);//加入5个小孩
circleSingleLinkedList.showBoy();
circleSingleLinkedList.countBoy(1,2,5);
}
}