约瑟夫环

package A;

public class Josephu {
public static void main(String[] args) {
Manage1 manage1=new Manage1();
manage1.addBox(5);
manage1.showBox();
manage1.countBox(1,2,5);
}
}

package A;

public class Manage1 {
Box first=null;

public void addBox(int nums){
if (nums<1){
System.out.println("nums必须大于或等于1");
return;
}
Box temp=null;
for (int i = 1; i <= nums; i++) {
Box box=new Box(i);
if (i==1){
first=box;
first.setNext(first);
temp=first;
}else {
temp.setNext(box);
box.setNext(first);
temp=box;
}
}
}

public void showBox(){
if (first==null){
return;
}
Box temp=first;
while (true){
System.out.println("bhao:"+temp.getId());
if (temp.getNext()==first){
break;
}
temp=temp.getNext();
}
}

public void countBox(int startId,int countNum,int nums){
if (first==null||startId<1||startId>nums){
System.out.println("输入有误");
return;
}
Box helper=first;
while (true){
if (helper.getNext()==first){
break;
}
helper=helper.getNext();
}
for (int j=0;j<startId-1;j++){
first=first.getNext();
helper=helper.getNext();
}
while (true){
if (helper==first){
break;
}
for (int j=0;j<countNum-1;j++){
first=first.getNext();
helper=helper.getNext();
}
System.out.println("小孩跳出圈"+first.getId());
first=first.getNext();
helper.setNext(first);
}
System.out.println("最后留在圈中的是"+first.getId());
}
}

package A;

public class Box {
private int id;
private Box next;
public Box(int id){
this.id=id;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public Box getNext() {
return next;
}

public void setNext(Box next) {
this.next = next;
}
}

posted @ 2021-07-25 10:22  朱在春  阅读(39)  评论(0编辑  收藏  举报