连夜编写的约瑟夫问题

以下是我用java做的约瑟夫问题,哈哈,不多说,先上代码!!!

呃,,有不足的地方请老师指出,,,呃,我好像还有两个实验没有交,,会尽快上交的!快哭了望老师海涵,再多宽恕几天。。。

package com.text1;

public class YSF {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CycLink cyclink=new CycLink();
		cyclink.setLen(9);
		cyclink.createLink();
		cyclink.setK(2);
		cyclink.setM(5);
		cyclink.Show();
		cyclink.play();
		


	}

}
class Child
{
	int no=0;
	Child nextChild;
	public Child(int no)
	{
		this.no=no;
	}
	
}
class CycLink
{
	//定义一个指向链表头的头结点
	Child firstChild=null;//指向第一个的引用不能动
	Child temp=null;
	int len=0;//表示共有多少个小孩
	int k=0;
	int m=0;
	//设置链表的大小
	public void setLen(int len)
	{
		this.len=len;
	}
	public void setK(int k)//设置从第几个人开始数数
	{
		this.k=k;
	}
	public void setM(int m)
	{
		this.m=m;
	}
	public void play()
	{
		Child temp=this.firstChild;
		//先找到开始数数的人k
		for(int i=1;i<k;i++)
		{
			temp=temp.nextChild;
		}
		
		while(this.len!=1)
		{
		//数m下
		for(int j=1;j<m;j++)
		{
			temp=temp.nextChild;
		}
		//找到要出圈的前一个
		Child temp2=temp;
		while(temp2.nextChild!=temp)
		{
			temp2=temp2.nextChild;
		}
		//将数到m的小孩退出圈
		temp2.nextChild=temp.nextChild;
		//让temp指向下一个数数的小孩
		temp=temp.nextChild;
		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;//存在一个firstChild指针指向第一个
				this.temp=ch;//存在一个temp指针指向第一个
			}
			else if(i==len)//最后一个
			{
				Child ch=new Child(i);
				temp.nextChild=ch;
				temp=ch;
				temp.nextChild=this.firstChild;
			}
			else
			{
				Child ch=new Child(i);//继续创建
				temp.nextChild=ch;
				temp=ch;
			}
		}
	}
	//打印该环形链表
	public void Show()
	{
		//定义另外一个中介
		Child temp=this.firstChild;
		do
		{
			System.out.println(temp.no+" ");
			temp=temp.nextChild;
		}while(temp!=this.firstChild);
	}
}<img src="https://img-blog.csdn.net/20141207211323031" alt="" />


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值