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 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 -- ;
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章