写出一个双向的循环链表,弄一个计数器,我定义的是到三的时候,自动删除当前节点,很简单。
packageCom;importjava.util.Scanner;/** 约瑟夫环问题,有n个人组成的圈,数到3的那个人出列,下个人继续从一开始*/publicclassJosephus {publicstaticvoidmain(String[] args) {
Scanner s=newScanner(System.in);intn =Integer.parseInt(s.nextLine());
Node first=newJosephus().startRun(n );intcount = 1;while(first.next !=first) {
first=first.next;
count++;if(count == 3) {
first.PRevious.next=first.next;
first.next.previous=first.previous;
first=first.next;
count= 1;
}
}
System.out.println("最后剩下来的数字为:"+first.n);
}publicNode startRun(intn) {
Node first=newNode();
first.previous=null;
first.n= n ;//这里给链表赋值,倒叙Node current =first;
Node last=first;while((--n)>0) {
current.next=newNode();
current=current.next;
current.n=n;
current.previous=last;
last=current;
}
current.next=first;
first.previous=current;returnfirst;
}classNode {intn ;
Node next;
Node previous;
}
}