Josephu问题
Boy类
class Boy{
private int id;
private Boy next;
public Boy(int id) {
this.id = id;
}
public Boy(Boy boy) {
this.id = boy.id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
@Override
public String toString() {
return "Boy{" +
"id=" + id +
'}';
}
}
CircleSingleLinkedList类
class CircleSingleLinkedList{
private Boy first = null;
public void addBoys(int nums){
if (nums < 1)
throw new RuntimeException("小孩数量有误!");
Boy boy = null;
Boy curBoy = null;
for (int i = 1; i <= nums; i++) {
boy = new Boy(i);
if (first == null){
first = new Boy(boy);
first.setNext(first);
continue;
}
curBoy = first;
while (curBoy.getNext().getId() != first.getId()){
curBoy = curBoy.getNext();
}
curBoy.setNext(boy);
boy.setNext(first);
}
}
public void showBoy(){
Boy curBoy = first;
System.out.println(first);
while (curBoy.getNext() != null){
curBoy = curBoy.getNext();
if (curBoy.getId() == first.getId())
return;
System.out.println(curBoy);
}
}
public void countBoy(int startId,int countNum,int nums){
addBoys(nums);
Boy curBoy = first;
int count = 1;
boolean startGame = false;
while (curBoy.getNext() != null){
curBoy = curBoy.getNext();
if (curBoy.getNext().getId() == first.getId())
break;
}
while (curBoy.getNext() != curBoy){
if (!startGame && count == startId){
count = 1;
startGame = true;
}
if (startGame && count == countNum){
System.out.println(curBoy.getNext() + "出圈");
curBoy.setNext(curBoy.getNext().getNext());
count = 1;
}
curBoy = curBoy.getNext();
count ++;
}
System.out.println(curBoy + "出圈");
}
}
代码测试
@Test
public void test(){
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.countBoy(1,2,5);
}
结果输出
Boy{id=2}出圈
Boy{id=4}出圈
Boy{id=1}出圈
Boy{id=5}出圈
Boy{id=3}出圈