丢手帕问题练习

/**
 * @author 司**
 * @功能:丢手帕问题
 * @time:2018.2.15
 * @问题描述:n个人围坐一圈,约定编号为K的人从1开始报数 ,数到m
 *         的那个人出列,他的下一位又从1开始报数,数到m的那个
 *         人又出列,直到最后一人
 * 
 */

package com.Nerd;

public class Demo1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CycLink cyclink=new CycLink();
		cyclink.setLen(5);
		cyclink.createLink();
		cyclink.setK(2);
		cyclink.setM(2);
		cyclink.show();
		cyclink.play();
	}

}

//定义一个小孩类
class Child
{
	int no;
	Child nextChile;
	public Child (int no)
	{
		this.no=no;
	}
}

// 环形链表
class CycLink
{
	//定义一个指向链表第一个小孩的引用
	Child firstChild =null;
	
	//创建一个临时的小孩指向
	Child temp=null;
	int len=0;
	
	int k=0;//k表示开始数数的人
	
	int m=0;//m是指数数的数
	
	//设置链表的大小
	public void setLen(int len)
	{
		this.len=len;
	}
	
	//设置开始数数的人
	public void setK(int k)
	{
		this.k=k;
	}
	
	//设置m
	public void setM(int m)
	{
		this.m=m;
	}
	
	//开始play
	public void play()
	{
		
		Child temp=this.firstChild;
		//1.先找到开始数数的人
		for(int i=1;i<k;i++)
		{
			temp=temp.nextChile;
			
		}
		while (this.len!=1){
		//2.数m下
		for(int i=1;i<m;i++)
		{
			temp=temp.nextChile;
		}
		//3.第m个人出列(即将这个人从环形链表中删除),
		//并从下一个人继续开始数数
		//如果设置成双向链表就好了,可是我们现在用的是单向的很烦。。。
		//3.1找到要删除孩子的上一个孩子
		Child temp2=temp;
		while (temp2.nextChile!=temp)
		{
			temp2=temp2.nextChile;
		}
		//3.2将数数第m个小孩出列
		temp2.nextChile=temp.nextChile;
		//3.3将temp指向下一个数数的小孩
		temp=temp.nextChile;
		
		this.len--;
		}
		
		//最后一个小孩
		System.out.println("最后一个小孩是:"+temp.no);
	}
	//初始化环形链表
	public void createLink()
	{
		for (int i=1;i<=len;i++)
		{
			if(i==1){
			//创建第一个小孩
			Child ch=new Child(i);
			
			//将两个指针都指向第一个孩子
			this.firstChild=ch;
			this.temp=ch;
			}else {
				if(i==len)
				{
					//继续创建小孩
					Child ch=new Child(i);
					temp.nextChile=ch;
					temp=temp.nextChile;
					temp.nextChile=this.firstChild;
				}else {
					
				
				//继续创建小孩
				Child ch=new Child(i);
				temp.nextChile=ch;
				temp=temp.nextChile;
				}
			}
		}
	}


//打印该环形链表
	public void show()
	{
	//定义一个临时的
		Child temp=this.firstChild;
		do{
			System.out.println(temp.no);
			temp=temp.nextChile;
			
		}while(temp!=this.firstChild);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值