约瑟夫问题
问题描述:设编号为1,2,…,n的n个人围坐一圈,规定编号为k(1<=k<=n)的人开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,以此类推,直到所有人出列,由此产生出一个出队编号的序列。
图解说明:

假设n=5,k=1,m=2
那么出圈的顺序就是:2->4->1->5->3
首先需要构建一个单向环形链表,并且实现遍历操作
代码如下
public class Josephu {
public static void main(String[] args) {
CircleSingleLinkedList cir = new CircleSingleLinkedList();
cir.addBoy(5);
cir.showBoy();
}
}
//创建一个环形的单向链表
class CircleSingleLinkedList{
//创建一个first节点,当前没有编号
private Boy first = null;
//添加小孩节点创建一个环形链表
public void addBoy(int num){
if(num < 1){
System.out.println("添加的数量无效");
}
Boy currBoy = null;
for (int i=1;i<=num;i++){
Boy boy = new Boy(i);
if (i == 1){
first = boy;
first.setNext(first);//构成环
currBoy = first;
}else{
currBoy.setNext(boy);
boy.setNext(first);
currBoy = boy;
}
}
}
//遍历当前环形链表
public void showBoy(){
if (first == null){
System.out.println("没有任何小孩");
}
Boy currBoy = first;//first指针不能动,借助辅助指针进行遍历
while (true){
System.out.println("小孩的编号为:" + currBoy.getNo());
if (currBoy.getNext() == first){
break;
}
currBoy = currBoy.getNext();
}
}
}
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;
}
}
结果如图所示

下面根据用户的输入,生成一个小孩出圈的顺序

如图假设n=5:一共有5个数据
k=1:从第一个人开始报数
m=2:每次数两次
思路
1.需求创建一个辅助变量helper,事先应该指向环形链表的最后这个节点
2.小孩报数前,先让first和helper移动k-1次
3.当小孩报数时,让first和helper指针同时移动m-1次
4.这时就可以将first指向的小孩节点出圈 first = first.next; helper.next = first;
原来first指向的节点就没有任何引用,就会被收回
代码如下
public void countBoy(int startNo,int countNum,int nums){
if (first == null || startNo < 1 || startNo > nums){
System.out.println("您所输入的参数无效");
}
Boy helper = first;
while (true){
if (helper.getNext() == first){
break;
}
helper = helper.getNext();//确定helper指向最后节点
}
//确定开始报数的位置
for (int i=0;i<startNo-1;i++){
first = first.getNext();
helper = helper.getNext();
}
//当小孩报数时让first和helper移动countNum-1次
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() + "留在圈内");
}
结果:

本篇文章是根据尚硅谷数据结构视频进行总结和代码实现,谢谢尚硅谷大学教会我java知识
约瑟夫问题是一个经典的数论问题,涉及使用单向环形链表来模拟过程。文章详细介绍了问题描述,例如当n=5,k=1,m=2时,出列顺序为2->4->1->5->3。通过代码展示了如何创建环形链表并实现遍历,以及如何按规则移除节点,最终得出出列序列。内容源于尚硅谷数据结构视频教程的总结与实践。
&spm=1001.2101.3001.5002&articleId=122024238&d=1&t=3&u=fbcd4282d235412caa3e518a7ac33905)
2195

被折叠的 条评论
为什么被折叠?



