java实现约瑟夫问题 求解
package com.oop;
public class Josephus {
public Josephus() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CycLink cl = new CycLink(6);
cl.createLink();
cl.show();
cl.setStart(1);
cl.setStep(5);
cl.play();
}
}
class Boys{
public int number;
public Boys nextBoys = null;
public Boys(int i){
this.number = i;
}
}
class CycLink{
public Boys firstBoys = null;
public Boys tmp=null;
public int len;
//起点
public int start = 0;
//步长
public int step = 0;
public CycLink(int len){
this.len = len;
}
public void setStep(int step){
this.step = step;
}
public void setStart(int start){
this.start = start;
}
public void createLink(){
for(int i = 0; i < len;i++){
if(i == 0){
Boys ch = new Boys(i);
this.firstBoys = ch;
this.tmp = ch;
}else{
if(i == len-1){
Boys ch = new Boys(i);
tmp.nextBoys = ch;
tmp = ch;
tmp.nextBoys = this.firstBoys;
}else{
Boys ch = new Boys(i);
tmp.nextBoys = ch;
tmp = ch;
}
}
}
}
public void show(){
Boys tmp = this.firstBoys;
do{
System.out.println(tmp.number);
tmp = tmp.nextBoys;
}while(tmp != this.firstBoys);
}
public void play(){
Boys tmp = this.firstBoys;
while(this.len != 1){
// 寻找起始位置
for(int i = 0;i < this.start-1; i++){
tmp = tmp.nextBoys;
}
//寻找被删除节点
for(int j = 0;j < this.step-1; j++){
tmp = tmp.nextBoys;
}
Boys tmp2 = tmp.nextBoys;
while(tmp2.nextBoys != tmp){
tmp2 = tmp2.nextBoys;
}
tmp2.nextBoys = tmp.nextBoys;
System.out.println(tmp.number);
tmp = tmp.nextBoys;
this.len -- ;
}
}
}