summer练习7.17

package com.hl.lianxi;

public class Josepu {
	public static void main(String[] args) {
		CycLink cyclink=new CycLink();
		cyclink.setLen(5);//链表长度
		cyclink.createLink();//创建链表
		cyclink.setK(1);//从第几个开始数,从第二个小孩开始数
		cyclink.setM(3);//数几下
		cyclink.show();
		cyclink.play();
	}
}
class Person {
	int num;//编号
	Person nextPerson=null;//引用类型,指向下一个小孩
	public Person(int num){
		//		给一个编号
		this.num=num;
	}
}
class CycLink{
//	先定义一个指向链表第一个小孩的引用
//	指向第一个小孩的引用,不能动
	Person firstPerson=null;
	Person temp=null;
	
	int len=0;//表示共有几个小孩
	int k=0;
	int m=0;
//	设置m数几下
	public void setM(int m){
		this.m=m;
	}	
//	设置链表的大小
	public void setLen(int len){
		this.len=len;
	}
//	设置第几个人开始数数
	public void setK(int k){
		this.k=k;
	}
//	开始play
	public void play(){
		Person temp=this.firstPerson;
//		1.先找到开始数数的人
		for(int i=1;i<k;i++){
			temp=temp.nextPerson;			
		}
		while(this.len!=1){
//			2.数m下
			for(int j=1;j<m;j++){
				temp=temp.nextPerson;
			}
			
//			找到要出圈的前一个小孩
			Person temp2=temp;
			while(temp2.nextPerson!=temp){
				temp2=temp2.nextPerson;
			}
			System.out.println("出圈的小孩编号:"+temp2.nextPerson.num);
//			3.将数到m的小孩,退出圈
			temp2.nextPerson=temp.nextPerson;
//			让temp指向下一个数数的小孩
			temp=temp.nextPerson;
			this.len--;
		}
		System.out.println("最后出圈的小孩:"+temp.num);
	}
	
//	初始化环形链表
	public void createLink(){
		for(int i=1;i<=len;i++){
//			创建第一个小孩
			if(i==1){
				Person ch=new Person(i);
				this.firstPerson=ch;
				this.temp=ch;
			}else if(i==len){
//				继续创建小孩
				Person ch=new Person(i);
				temp.nextPerson=ch;
				temp=ch;
				temp.nextPerson=this.firstPerson;
			}else{
//				继续创建小孩
				Person ch=new Person(i);
				temp.nextPerson=ch;
				temp=ch;
			}
		}
	}
	
//	打印环形链表
	public void show(){
//		定义一个跑龙套
		Person temp=this.firstPerson;
		do{
			System.out.println(temp.num+"");
			temp=temp.nextPerson;
		}while(temp!=this.firstPerson);
	}
	
}

josephu问题,参考百度,自己理解。

结果

猜你喜欢

转载自blog.csdn.net/LinLin_Hou/article/details/81092163