约瑟夫问题
- 1,2,3,4… n个人围成一圈,从k开始报数,第m个人数列,循环,直到所有人出列。产生一个出队编号
public class Josephus {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.add(5);
circleSingleLinkedList.show();
circleSingleLinkedList.countBoy(1,2);
}
}
class CircleSingleLinkedList {
private Boy first;
public void add(int nums) {
if (nums < 1) {
return;
}
Boy curBoy = null;
for (int i = 1; i <= nums; i++) {
Boy boy = new Boy(i);
if (boy.getNo() == 1) {
first = boy;
first.setNext(first);
curBoy = first;
} else {
curBoy.setNext(boy);
curBoy = boy;
curBoy.setNext(first);
}
}
}
public void show() {
if (first == null) {
return;
}
Boy curBoy = first;
while (true) {
System.out.println(curBoy);
if (curBoy.getNext() == first) {
break;
}
curBoy = curBoy.getNext();
}
}
public void countBoy(int startNo, int countNum) {
if (startNo < 1 ) {
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++) {
first = first.getNext();
helper = helper.getNext();
}
while (true) {
if (helper == first) {
System.out.println("出圈节点:" + first);
break;
}
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.println("出圈节点:" + first);
first = first.getNext();
helper.setNext(first);
}
}
}
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 +
'}';
}
}