Josephu(约瑟夫、约瑟夫环) 问题
Josephu 问题为:设编号为 1,2,… n 的 n 个人围坐一圈,约定编号为 k(1<=k<=n)的人从 1 开始报数,数 到 m 的那个人出列,它的下一位又从 1 开始报数,数到 m 的那个人又出列,依次类推,直到所有人出列为止,由 此产生一个出队编号的序列。 提示:用一个不带头结点的循环链表来处理 Josephu 问题:先构成一个有 n 个结点的单循环链表,然后由 k 结 点起从 1 开始计数,计到 m 时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从 1 开始计数,直 到最后一个结点从链表中删除算法结束。
# 约瑟夫问题-小孩出圈的思路分析图
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList list = new CircleSingleLinkedList();
list.addBoy(5);
list.showBoy();
list.countBot(1,2,5);
}
}
class CircleSingleLinkedList {
private Boy first = null;
//添加节点 构建成一个环形链表
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;//让curBoy指向第一个小孩 因为first不能动
} 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();
}
}
//根据用户的输入 计算出小孩出圈的顺序
/*
* startNo k从第几个小孩开始数数
* countNo m数几下
* nums 表示最初有多少小孩在圈中
* */
public void countBot(int startNo, int countNo, int nums) {
//数据校验
if (first == null || startNo < 1 || startNo > nums) {
System.out.println("数据有误 ");
return;
}
//创建一个辅助指针 帮助完成小孩出圈
Boy helper = first;
while (helper.getNext() != first) {
helper = helper.getNext();
}
//小孩报数前 先让first和helper移动 k-1 次
for (int i = 1; i < startNo; i++) {
first = first.getNext();
helper = helper.getNext();
}
//开始报数 first和helper移动 m-1 次 然后出圈
while (true){
if (first==helper){//说明圈中只有一人
break;
}
//first和helper同时移动 m-1 次
for (int i = 0; i <countNo-1 ; i++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩%d出圈\n",first.getNo());
first=first.getNext();
helper.setNext(first);
}
System.out.printf("最后留在圈中的小孩编号是%d\n",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;
}
}