本文主要是介绍Josephus 问题的代码实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java实现约瑟夫问题 求解
package com.oop;public class Josephus {public Josephus() {// TODO Auto-generated constructor stub}public static void main(String[] args) {// TODO Auto-generated method stubCycLink 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 -- ;}}
}
这篇关于Josephus 问题的代码实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!