一. 基本介绍
-
约瑟夫问题。
Joseph问题为:设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。
-
代码实现思路。
用一个不带头结点的循环链表来处理Joseph问题:先构成一个有n个结点的单循环链表,然后由k结点起从1开始计数,计到m时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从1开始计数,直到最后一个结点从链表中删除算法结束。
二. 代码实现
- Boy节点
package datastructure.linkedlist.joseph;
public class Boy {
private int no; // 编号
private Boy next; // 指向下一个Boy节点
public Boy(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
@Override
public String toString() {
return "Boy{" +
"no=" + no +
'}';
}
}
- 环形链表
package datastructure.linkedlist.joseph;
public class CircleLinkedList {
private Boy first = null;
/**
* 向环形链表中添加num个节点
* @param num 要添加节点的个数
*/
public void add(int num) {
if (num <= 0) {
System.out.println("输入的数字不符合规范!");
return;
}
// 指向最后添加的节点
Boy currentBoy = null;
// 循环num次,每次创建一个boy节点并
for (int i = 1; i <= num; i++) {
Boy boy = new Boy(i);
if (i == 1) {
// 添加第一个boy节点的时候,boy自己组成一个环形链表
first = boy;
currentBoy = boy;
currentBoy.setNext(first);
} else {
// 添加后面的节点
currentBoy.setNext(boy);
// 最后添加的节点的next指向first
boy.setNext(first);
// current指向刚添加也就是最后添加的节点
currentBoy = boy;
}
}
}
// 遍历环形链表
public void showBoy() {
if (first == null) {
System.out.println("此链表为空!");
return;
}
// 打印环形链表的first节点
System.out.println(first);
Boy currentBoy = first.getNext();
// 依次打印剩下的节点
while (currentBoy != first) {
System.out.println(currentBoy);
currentBoy = currentBoy.getNext();
}
}
/**
* 根据用户的输入,计算出小孩出圈的顺序
* @param startNo 开始小孩的编号
* @param count 数几下
* @param nums 圈里小孩的个数
*/
public void countBoy(int startNo, int count, int nums) {
if (startNo <= 0 || count <= 0 || startNo > nums) {
System.out.println("输入参数有误!");
return;
}
if (first == null) {
System.out.println("链表为空, 不能进行此操作!");
return;
}
// 刚开始让current指针指向first指针的前一个 也就是环形链表的最后一个
Boy currentBoy = first;
while (true) {
if (currentBoy.getNext() == first) {
break;
}
currentBoy = currentBoy.getNext();
}
// 让first指针指向第一个数数的小孩 current指向first的前一个
for (int i = 1; i < startNo; i++) {
first = first.getNext();
currentBoy = currentBoy.getNext();
}
// 小孩出圈 当current与first指向同一个小孩的时候,表示环形链表中只有一个小孩,退出循环
while (currentBoy != first) {
// 寻找每次要出圈的小孩
for (int j = 1; j < count; j++) {
currentBoy = currentBoy.getNext();
first = first.getNext();
}
System.out.println("出圈的小孩是:" + first);
// 把已经出圈的小孩从环形链表中移除
first = first.getNext();
currentBoy.setNext(first);
}
// 输入最后一个小孩
System.out.println("最后出圈的小孩是:" + first);
}
}
- 测试类
package datastructure.linkedlist.joseph;
public class CircleLinkedListDemo {
public static void main(String[] args) {
CircleLinkedList circleLinkedList = new CircleLinkedList();
// 添加节点
circleLinkedList.add(20);
// 遍历
// circleLinkedList.showBoy();
// 出圈
circleLinkedList.countBoy(1, 3, 20);
}
}