约瑟夫(Josephu)问题(丢手帕问题)
1、Josephu问题为:设编号为1,2,。。。n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,直到所有人出列为止,由此产生一个出队编号的序列。
Josephu问题的解决:
用一个不带头结点的循环链表来处理Josephu问题:先构成一个有n个结点的单循环链表,然后由K结点开始从1开始计数,计到m时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从1开始计数,直到最后一个结点从链表中删除。
1、需要创建一个辅助变量helper,始终跟在first后面。
2、当小孩报数时,让first和helper指针同时移动m-1次,这时first指向的节点即为该出圈的节点
3、让first指向的小孩节点出圈
first = first.next;
helper.next = first;
原来first指向的节点没有任何引用,就会被回收。
public class Joshphuu {
public static void main(String[] args) {
CircleSingleLinkedList list = new CircleSingleLinkedList();
list.addBoy(10);
list.show();
System.out.println("******************");
list.countBoy(1, 3, 10);
}
}
class CircleSingleLinkedList {
private Boy first = null;
public CircleSingleLinkedList() {
}
/**
* 向链表中添加指定个数的节点
*
* @param nums 节点数
*/
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 (first == null) {
first = boy;
first.setNext(first);
curBoy = first;
} else {
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;
}
}
}
public void show() {
if (first == null) {
System.out.println("链表为空~");
}
Boy curBoy = first;
while (true) {
if (curBoy.getNext() == first) {
System.out.printf("小孩的编号是:%d\n", curBoy.getNo());
break;
}
System.out.printf("小孩的编号是:%d\n", curBoy.getNo());
curBoy = curBoy.getNext();
}
}
/**
* @param startNo 从编号startNo开始数数
* @param k 每次数到k就有一人出圈
* @param nums 总人数
*/
public void countBoy(int startNo, int k, int nums) {
if (startNo < 1 || startNo > nums || first == null) {
System.out.println("参数输入有误,请重新输入");
return;
}
Boy helper = first;
while (true) {
if (helper.getNext() == first) {
break;
}
helper = helper.getNext();
}
for (int i = 0; i < startNo - 1; i++) {
helper = first;
first = first.getNext();
}
while (first.getNext() != first) {
for (int i = 0; i < k - 1; i++) {
helper = first;
first = first.getNext();
}
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;
}
@Override
public String toString() {
return "Boy{" +
"no=" + no +
'}';
}
}
小孩的编号是:1
小孩的编号是:2
小孩的编号是:3
小孩的编号是:4
小孩的编号是:5
小孩的编号是:6
小孩的编号是:7
小孩的编号是:8
小孩的编号是:9
小孩的编号是:10
******************
最后留在圈中的小孩编号是4