约瑟夫问题是个有名的问题:N个人围成一圈,从第m个开始报数,第k个将出队,最后剩下一个,其余人都将出队。
1.构建一个单向循环的链表
2.遍历环形数组
public class Yuesefu {
public static void main(String args[]) {
Circle c=new Circle();
c.add(6);
c.show();
}
}
class Circle{
private Boy first=new Boy(0);
public void add(int nums) {
if(nums<1) {
System.out.println("重输");
}
Boy curBoy=null; //定义指针,辅助构建环形链表
for(int i=1;i<=nums;i++) {
Boy boy=new Boy(i);
if(i==1) { //第一个小孩,自己形成环
first=boy;
boy.setNext(first);
curBoy=boy;
}
else {
curBoy.setNext(boy);
boy.setNext(first);
curBoy=boy;
}
}
}
public void show() {
if(first==null) {
return ;
}
Boy curBoy=first;
while(curBoy!=null) {
System.out.printf("%d号小孩\n",curBoy.getNo());
if(curBoy.getNext()==first) { //循环一圈后,跳出
break;
}else {
curBoy=curBoy.getNext();
}
}
}
}
class Boy{
int no;
Boy next;
public Boy(int no) {
this.no=no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}
结果:
1号小孩
2号小孩
3号小孩
4号小孩
5号小孩
6号小孩