Java代码中的countBoy方法就是用于解决约瑟夫环问题的
力扣相关题目:LCR 187. 破冰游戏 - 力扣(LeetCode)
package DataStructure;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 86178
* Date: 2024-02-11
* Time: 14:48
*/
public class JosephuDemo {
public static void main(String[] args) {
//todo 单向环形链表
CircleList cl=new CircleList();
cl.AddElem(5);
cl.list();
System.out.println("-----------------------------");
//cl.countBoy(1,2,5);// 2 4 1 5 3
System.out.println("-----------------------------");
cl.countBoy(2,2,5);// 3 5 2 1 4
}
}
class CircleList{
//todo 创建一个first节点 无编号
private Boy first=new Boy(-1);
public Boy getFirst(){
return first;
}
//todo 添加
public void AddElem(int n){
//对n进行数据校验
if(n<1){
System.out.println("n值错误");
return;
}
//todo cur指向现有链表的最后一个节点
//todo curBoy指向最新的节点
//todo first指向第一个节点
Boy curBoy=new Boy(-1);
Boy cur=new Boy(-1);
for(int i=1;i<=n;i++){
curBoy=new Boy(i);//创建新的节点
if(i==1){
first=curBoy;
first.setNext(first);
cur=curBoy;
}else{
cur.setNext(curBoy);
cur=curBoy;
cur.setNext(first);
}
}
}
//todo startNo是最先开始报数的小孩编号
//todo countNum是约瑟夫问题中的M
//todo nums是最初有多少个小孩
public void countBoy(int startNo,int countNum,int nums){
//校验参数是否正确
if(startNo<1 || startNo>nums || first==null){
System.out.println("参数输入有误");
return ;
}
//创建一个辅助指针 指向环形链表的最后一个节点
Boy helper=new Boy(-1);
Boy cur=first;
while(cur.next!=first){
cur=cur.next;
}
helper=cur;//指向了链表的最后一个节点
//todo 先让first和helper指向开始节点和开始节点的前一位
for(int i=0;i<startNo-1;i++){
first=first.next;
helper=helper.next;
}
while(helper!=first){
for(int i=0;i<countNum-1;i++){
first=first.next;
helper=helper.next;//一起走了m-1次
}
//先打印出圈的元素
System.out.println(first);
first=first.next;
helper.next=first;
}
System.out.println(first);
}
public void list(){
//不断地遍历输出
if(first==null){
System.out.println("链表为空");
return;
}
Boy cur=first.next;
System.out.println(first);
while(cur!=first){
System.out.println(cur);
cur=cur.next;
}
}
}
//创建一个Boy类
class Boy{
private int no;
public Boy next;
public Boy(int n){
this.no=n;
}
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;
}
//todo 显示节点信息
@Override
public String toString(){
return "Boy[no="+no+" next.no="+next.no+"]";
}
}