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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值