定义人类结构体
public class people {
int num;
people next;
public people(int num) {
this.num = num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public people getNext() {
return next;
}
public void setNext(people next) {
this.next = next;
}
}
核心代码
public class JosefulLikeList {
people head;
public void addpeople(int num)
{
if(num<1)
{
System.out.println("人数不符合开始规定");
return;
}
people pos=null;
for(int i=1;i<=num;i++)
{
people people= new people(i);
if(i==1)
{
head = people;
pos=head;
head.next=head;
}
else
{
pos.next=people;
people.next=head;
pos=people;
}
}
}
public void showLikelist()
{
if(head.next==null)
{
System.out.println("不符合规定");
return;
}
people pos=head;
while(true)
{
System.out.println(pos.num);
if(pos.next==head)
{
break;
}
pos=pos.next;
}
}
public void chuquan(int startnum,int all,int ci)
{
if(head.next==null||startnum<1||startnum>all)
{
System.out.println("不符合标准");
return;
}
people helper=head;
while(true)
{
if(helper.next==head)
{
System.out.println("找到了head的上一个人");
break;
}
helper=helper.next;
}
for(int i=1;i<startnum;i++)
{
head=head.next;
helper=helper.next;
}
while(true)
{
if(head==helper)
{
System.out.println(head.num);
break;
}
for(int i=1;i<ci;i++)
{
head=head.next;
helper=helper.next;
}
System.out.printf("第%d号出圈\n",head.num);
head=head.next;
helper.next=head;
}
System.out.printf("最后留下来的是%d",head.num);
}
}
测试
public class test {
public static void main(String[] args) {
JosefulLikeList josefulLikeList = new JosefulLikeList();
josefulLikeList.addpeople(5);
josefulLikeList.showLikelist();
josefulLikeList.chuquan(1,5,2);
}
}
标签:num,helper,people,int,约瑟夫,链表,循环,next,public
From: https://www.cnblogs.com/jinnice/p/16846432.html