创建环形链表的思路图解图解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a82410e4763852907a8434137d6476c2.png)
约瑟夫问题-小孩出圈的思路分析图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5ceb79fab9141a19ee0c1c8f017e42af.png)
约瑟夫问题的代码实现
package com.atguigu.linklist;
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.showBoy();
circleSingleLinkedList.countBoy(1,2,5);
}
}
class CircleSingleLinkedList{
private Boy first=new Boy(-1);
public void addBoy(int 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;
first.setNext((first));
curBoy=first;
}else{
curBoy.setNext(boy);
boy.setNext(first);
curBoy=boy;
}
}
}
public void showBoy(){
if(first==null){
System.out.println("链表为空,没有任何小孩");
return;
}
Boy curBoy=first;
while(true){
System.out.printf("小孩的编号%d\n",curBoy.getNo());
if(curBoy.getNext()==first) {
break;
}
curBoy=curBoy.getNext();
}
}
public void countBoy(int starrNo,int countNum,int nums){
if(first==null||starrNo<1||starrNo>nums){
System.out.println("参数输入有误,请重新输入");
return;
}
Boy helper=first;
while(true){
if(helper.getNext()==first){
break;
}
helper=helper.getNext();
}
for(int j=0;j<starrNo-1;j++){
first=first.getNext();
helper=helper.getNext();
}
while(true){
if(helper==first){
break;
}
for(int j=0;j<countNum-1;j++){
first=first.getNext();
helper=helper.getNext();
}
System.out.println("小孩出圈"+first.getNo());
first=first.getNext();
helper.setNext(first);
}
System.out.println("最后留在圈中的小孩编号"+first.getNo());
}
}
class Boy{
private int no;
private Boy next;
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;
}
}