/**
* 约瑟夫问题
*
* @author Mulun
*/
public class Josephu {
public static void main(String[] args) {
CircleSingleLinkedList csl = new CircleSingleLinkedList();
// 创建链表
csl.addBoy(25);
// 显示链表
csl.list();
// 执行出圈
csl.countBoy(1, 2, 25);
}
}
/**
* 环形单向链表
*/
class CircleSingleLinkedList {
/**
* 创建first节点,当前没有值
*/
private Boy first = null;
/**
* 添加节点,构建环形链表
*
* @param nums 有多少个节点
*/
public void addBoy(int nums) {
// 校验nums
if (nums < 1)
throw new RuntimeException("nums的值不正确");
// 定义指针,帮助构建环形链表
Boy curBoy = null;
// 使用for循环创建环形链表
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 list() {
if (first == null)
throw new RuntimeException("链表为空");
// 定义指针,指向当前节点
Boy temp = first;
while (true) {
System.out.printf("小孩的编号 %d \n", temp.getNo());
// 如果当前指针的下一个节点是头部,则表示遍历完毕
if (temp.getNext() == first)
break;
// 指针后移
temp = temp.getNext();
}
}
/**
* 根据用户的输入,计算出小孩出圈的顺序
*
* @param startNo 从第几个节点开始数
* @param countNum 数几下
* @param nums 最初共有几个节点
*/
public void countBoy(int startNo, int countNum, int nums) {
// 数据校验
if (first == null || startNo < 1 || startNo > nums)
throw new IllegalArgumentException("参数异常");
// 定义指针,指向队列尾部
Boy helper = first;
// 遍历确定指针位置
while (true) {
// 判断是否指向队列尾部
if (helper.getNext() == first)
break;
// 指针后移
helper = helper.getNext();
}
// 头部指针和尾部指针,移动 (startNo - 1) 次
for (int i = 0; i < startNo - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
// 报数开始移动指针,次数足够则出圈
while (true) {
// 判断是否只有一个节点
if (helper == first)
break;
// 移动指针,同时移动 (countNum - 1) 次
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
// 当前first节点会指向要出圈的节点
System.out.printf("小孩%d出圈\n", first.getNo());
// 执行出圈
// first指向要出圈节点的下一个节点
first = first.getNext();
// helper的 next 指向新的first
helper.setNext(first);
}
// 最后一个节点
System.out.printf("最后留在圈中的小孩编号是%d \n", first.getNo());
}
}
/**
* 环形列表节点,一个Boy表示一个节点
*/
@Getter
@Setter
class Boy {
/**
* 编号
*/
private int no;
/**
* 指向下一个节点指针
*/
private Boy next;
/**
* 创建节点
*
* @param no
*/
public Boy(int no) {
this.no = no;
}
}
约瑟夫问题
最新推荐文章于 2024-08-12 16:47:32 发布