黑马程序员——约瑟夫环问题

---------------------- android培训java培训、期待与您交流! ----------------------/**
*李见黎
*2012-3-14
*约瑟夫环问题
*/


public class  Josephu
{
public static void main(String[] args) 
{
CycLink cl=new CycLink();
cl.setLen(5);
cl.CreateCyc();
cl.Show();
cl.setK(2);
cl.setM(2);
cl.Play();
}
}
/**
 * 循环列表类
 * @author 李见黎
 *
 */
 class CycLink
{
int Len;
Child firstChild=null; //初始化第一个元素对象,第一个指针不变
Child temp=null;     //定义一个游标,非常有用

int k=0;
public void setK(int k)
{
this.k=k;
}

int m=0;
public void setM(int m)
{
this.m=m;
}
public void setLen(int len)
{
this.Len=len;
}
/**
* 创建循环链表
*/
public void CreateCyc()
{
for(int i=1;i<=this.Len;i++)
{
if(i==1)
{//是第一个元素,将第一个对象的引用付给firstChild和temp
Child ch=new Child(i);
this.firstChild=ch;
this.temp=ch;

}
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 Play()
{
Child temp=this.firstChild;
//1.找到开始元素K
for(int i=1;i<k;i++)
{//都是从1开始的
temp=temp.nextChild;
}
//2.数M个元素

while(Len!=1)
{
for(int j=1;j<m;j++)
{
temp=temp.nextChild;
}
//找到要出圈的前一个元素
Child temp2=temp;

while(temp2.nextChild!=temp)
{
temp2=temp2.nextChild;
}

//2.第M个元素出圈
temp2.nextChild=temp.nextChild;
temp=temp.nextChild;

this.Len--;
}
//最后一个元素
System.out.println("最后一个出圈的是:"+temp.num);

}
/**
* 显示函数
*/
public void Show()
{
Child temp=this.firstChild; //定义一个游标,可以使firstChild不改变,之改变游标就可以


do
{
System.out.println(temp.num);
temp=temp.nextChild; //移动tempt
}
while (temp!=this.firstChild);
}


}
/**
 * 元素类,属性有,序列号,指向下一个的引用
 * @author 李见黎
 */
 class Child
{
int num;
Child nextChild=null;  //非常重要,很难想到,创建指向下一个的指针


public Child(int num)
{
this.num=num;
}
}--------------------- android培训java培训、期待与您交流! ----------------------详细请查看: http://edu.csdn.net/heima
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值