约瑟夫问题(Josephu)(Java)
问题描述
设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。
提示
用一个不带头结点的循环链表来处理Josephu问题:先构成一一个有n个结点的单循环链表,然后由k结点起从1开始计数,计到m时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从1开始计数,直到最后一个结点从链表中删除算法结束。
解题思路
代码如下
public class Josephu {
public static class Node {
private int no;// 编号
private Node next; // 指向下一个节点
public Node(int no) {
this.no = no;
}
public int getno() {
return no;
}
public void setno(int no) {
this.no = no;
}
public Node getnext() {
return next;
}
public void setnext(Node next) {
this.next = next;
}
}
// 创建一个环形的单向链表
public static class circlelist {
private static Node first = null; // 创建一个first节点,当前没有编号
public void add(int nums) {// 添加小孩节点,构建成一个环形的链表
if (nums < 1) {
System.out.println("nums的值不正确");
return;
}
Node curNode = null; // 辅助指针,帮助构建环形链表
for (int i = 1; i <= nums; i++) {// 使用for来创建我们的环形链表
Node Node = new Node(i);// 根据编号,创建小孩节点
if (i == 1) {// 如果是第一个小孩
first = Node;
first.setnext(first); // 构成环
curNode = first; // 让curNode指向第一个小孩
} else {
curNode.setnext(Node);//
Node.setnext(first);//
curNode = Node;
}
}
}
// 遍历当前的环形链表
public static void show() {
if (first == null) {// 判断链表是否为空
System.out.println("没有任何小孩~~");
return;
}
Node curNode = first;// 因为first不能动,因此我们仍然使用一个辅助指针完成遍历
while (true) {
System.out.printf("小孩的编号 %d \n", curNode.getno());
if (curNode.getnext() == first) {// 说明已经遍历完毕
break;
}
curNode = curNode.getnext(); // curNode后移
}
}
// 根据用户的输入,计算出小孩出圈的顺序
public void count(int start, int Num, int nums) {
if (first == null || start < 1 || start > nums) {// 先对数据进行校验
System.out.println("参数输入有误, 请重新输入");
return;
}
Node helper = first;// 创建要给辅助指针,帮助完成小孩出圈
while (true) {
if (helper.getnext() == first) { // 说明helper指向最后小孩节点
break;
}
helper = helper.getnext();
}
for(int j = 0; j < start - 1; j++) {//小孩报数前,先让 first 和 helper 移动 k - 1次
first = first.getnext();
helper = helper.getnext();
}
while(true) {
if(helper == first) { //说明圈中只有一个节点
break;
}
for(int j = 0; j < Num - 1; j++) {//让 first 和 helper 指针同时 的移动 Num - 1
first = first.getnext();
helper = helper.getnext();
}
System.out.printf("小孩%d出圈\n", first.getno());//这时first指向的节点,就是要出圈的小孩节点
first = first.getnext();//这时将first指向的小孩节点出圈
helper.setnext(first); //
}
System.out.printf("最后留在圈中的小孩编号%d \n", first.getno());
}
}
public static void main(String[] args) {
// 测试看看构建环形链表,和遍历
circlelist circlelist = new circlelist();
circlelist.add(8);//添加8个结点
circlelist.show();//遍历显示
circlelist.count(3, 2, 8); //从3号开始每次地问个出列,共8个人
}
}