:约瑟夫问题-环形链表
package com.atguigu.linkedlist;
import java.lang.Thread.State;
public class Josephu {
public static void main(String[] args) {
// TODO Auto-generated method stub
CircleSingleLinkedList c = new CircleSingleLinkedList();
c.addBoy(5);//
c.showBoy();
// c.countBoy(1,2,5);//2-4-1-5-3
c.countBoy(2,3,5);//4-2-1-3-5
c.showBoy();
}
}
//创建一个环形的单向链表
class CircleSingleLinkedList{
//创建一个first节点,当前没有编号
private Boy first = new Boy(-1);
//添加小孩节点,构建成一个环形的链表
public void addBoy(int nums) {
//nums 做一个数据校验
if(nums<1) {
System.out.println("nums的值不正确");
return;
}
Boy curBoy = null;//辅助指针,帮助构建环形链表
for(int i=1;i<=nums;i++) {
//根据编号创建小孩节点
Boy boy = new Boy(i);
//如果是第一个小孩
if(i==1) {
first = boy;
boy.setNext(first);//构成环
curBoy = first;//让curBoy指向第一个小孩节点
}else {
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;//指向尾部,
}
}
}
//遍历当前的环形链表
public void showBoy() {
//判断是否空
if(first == null) {
System.out.println("链表空~~~");
return;
}
//因为first指针不能动,使用辅助指针(变量)
Boy curBoy = first;
while(true) {
System.out.printf("小孩编号 %d \n",curBoy.getNo());
if(curBoy.getNext() == first) {
break;
}
curBoy = curBoy.getNext();//curBoy后移
}
}
//根据用户的输入,计算出小孩出圈的顺序
/**
* @param startNo 表示从第几个开始数
* @param countNum 表示数几次
* @param nums 表示初始人数
*/
public void countBoy(int startNo,int countNum,int nums) {
if(first == null || startNo<1 || startNo>nums) {
System.out.println("参数有误,请重新输入");
return;
}
//创建辅助指针
Boy helper = first;
while(true) {
if(helper.getNext()==first) {
break;
}
helper = helper.getNext();
}
//报数前,先让first和helper移动startNo-1次,此时first指向第一个报数者
for(int j=0;j<startNo-1;j++) {
first = first.getNext();
helper = helper.getNext();
}
//报数时,让first 和 heper 同时移动countNum-1次,然后出圈,直到仅剩一个节点
while(true) {
if(helper==first) {//只有一个节点
break;
}
//让first 和 heper 同时移动countNum-1次
for(int j=0;j<countNum-1;j++) {
first = first.getNext();
helper = helper.getNext();
}
//这时first指向的节点就是要出圈的节点
System.out.printf("小孩 %d 出圈\n",first.getNo());
//
first =first.getNext();
helper.setNext(first);
}
System.out.printf("最后留下的小孩编号 %d \n",helper.getNo());
}
}
//创建一个Boy类,表示一个节点
class Boy{
private int no;//编号
private Boy next;//指向下一节点,默认null
//构造器
public Boy(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}