public class Demo3 {
public static void main(String[] args) {
CycLink cyclink=new CycLink();
CycLink.setLen(10);
CycLink.CreateLink();
CycLink.show();
CycLink.setK(3);
CycLink.setM(3);
CycLink.play();
}
}
class Child
{
int no;
Child nextChild=null;
public Child(int no)
{
//給一個編号
this.no=no;
}
}
//環形連結清單
class CycLink
{
//先定義一個指向連結清單第一個小孩的引用
//指向第一個小孩的引用不能動
Child firstChild=null;
Child 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()
{
Child temp=this.firstChild;
//先找到開始數數的人
for(int i=1;i<k;i++)
{
temp=temp.nextChild;
}
while (this.Len!=1)
{
//2.數m下
for (int j=1;j<m;j++)
{
temp=temp.nextChild;
}
//找到要出圈的前一個小孩
Child temp2=temp;
while(temp2.nextChild != temp)
{
temp2=temp2.nextChild;
}
//3.将數到的小孩退出圈
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;
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 show()
{
//定義一個跑龍套的
Child temp=this.firstChild;
do
{
System.out.println(temp.no);
temp=temp.nextChild;
}while(temp != this.firstChild);
}
}
轉載于:https://blog.51cto.com/11154783/1784275