约瑟夫问题

问题描述:n个人(编号0~(n-1)),从0开始报数,报到(m-1)的退出,剩下的人继续从0开始报数。求胜利者的编号。

public class Child {

	int no;
	Child nextChild = null;
	
	public Child(int no){
		this.no = no;
	}
}
public class CycLink {

	Child firstChild = null;
	int len = 0;
	Child temp = null;
	int m = 0;
	
	//设置队列长度
	public void setLen(int len){
		this.len =len;
	}
	
	//设置第几个人出列
	public void setM(int m){
		this.m = m;
	}
	
	//创建队列,使用循环链表
	public void createCyc(){
		
		for(int i=1;i<=len;i++){
			Child ch = new Child(i);
			//第一个人为链表的第一个
			if(i==1){
				temp = firstChild = ch;
			}
			else{
				temp.nextChild = ch;
				temp = ch;
				//如果是最后一个人就链接到第一个人
				if(i==len){
					temp.nextChild = firstChild;
				}
			}
		}
		show();
	}
	
	public void play(){
		
		//定义两个指针,temp1用来找到第m个人的前一个人,temp2用来找到第m个人
		Child temp1 = firstChild;
		Child temp2 = null;
		
		for(int j=len;j>1;j--){
			//找到第m个人的前一个人
			for(int i=1;i<m-1;i++){
				temp1 = temp1.nextChild;
			}
			//把第m个人的前一个人链接到第m个人的后一个人
			temp2 = temp1.nextChild;
			temp1.nextChild = temp2.nextChild;
			temp1 = temp2.nextChild;
		}
		
		System.out.println("结果是:" + temp1.no);
	}
	
	public void show(){
		
		Child temp3 = this.firstChild;
		do{
			System.out.print(temp3.no + " ");
			temp3 = temp3.nextChild;
		} while(temp3 != this.firstChild);
		
	}
			
}




public class Josefu {


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		CycLink cyc = new CycLink();
		cyc.setLen(10);
		cyc.createCyc();
		cyc.setM(4);
		cyc.play();


	}


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值