JosephuProblem.java
package DataStructures.linkedList;
public class JosephuProblem {
private Boy first;
public void countBoy(int startNo,int countNum,int nums){
if (first == null || startNo < 1 || startNo > nums){
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 (helper == first){
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.println("小孩" + first.getNo() + "出圈");
first = first.getNext();
helper.setNext(first);
}
System.out.println("最后留在圈中的小孩为" + first.getNo() + "号小孩");
}
public void addBoy(int count){
if (count < 1){
System.out.println("请重新输入");
return;
}
Boy cur = null;
for (int i = 1; i < count; i++) {
Boy boy = new Boy(i);
if (i == 1){
first = boy;
boy.setNext(first);
cur = first;
}else{
cur.setNext(boy);
boy.setNext(first);
cur = boy;
}
}
}
public void showBoy(){
if (first == null){
System.out.println("链表为空");
return;
}
Boy cur = first;
while (true){
System.out.println("当前为第" + cur.getNo() + "个节点");
if (cur.getNext() == first){
break;
}
cur = cur.getNext();
}
}
}
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;
}
}