Josephu问题
设编号为1,2,...n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,至到所有人出列为止,由此产生一个出队编号的序列。
代码
public class Josephu {
public static void main ( String[ ] args) {
CircleSingleLinkedList list = new CircleSingleLinkedList ( ) ;
list. addBoy ( 10 ) ;
list. show ( ) ;
list. countBoy ( 2 , 5 ) ;
}
}
class CircleSingleLinkedList {
private Boy first = null;
public void addBoy ( int num) {
Boy currentBoy = null;
for ( int i = 1 ; i <= num; i++ ) {
Boy boy = new Boy ( i) ;
if ( i == 1 ) {
first = boy;
boy. setNext ( first) ;
currentBoy = boy;
} else {
currentBoy. setNext ( boy) ;
currentBoy = boy;
currentBoy. setNext ( first) ;
}
}
}
public void show ( ) {
if ( first == null) {
System. out. println ( "链表为空" ) ;
return ;
}
Boy currentBoy = first;
while ( true ) {
System. out. println ( currentBoy) ;
if ( currentBoy. getNext ( ) == first) {
return ;
} else {
currentBoy = currentBoy. getNext ( ) ;
}
}
}
public void countBoy ( int startNo, int countNum) {
if ( first == null || countNum < 1 ) {
System. out. println ( "参数有误" ) ;
return ;
}
Boy helper = first;
while ( true ) {
if ( helper. getNext ( ) == first) {
break ;
}
helper = helper. getNext ( ) ;
}
for ( int i = 0 ; i < startNo- 1 ; i++ ) {
first = first. getNext ( ) ;
helper = helper. getNext ( ) ;
}
while ( true ) {
if ( helper == first) {
System. out. println ( "last" + helper) ;
break ;
}
for ( int i = 0 ; i < countNum - 1 ; i++ ) {
first = first. getNext ( ) ;
helper = helper. getNext ( ) ;
}
System. out. println ( first) ;
first = first. getNext ( ) ;
helper. setNext ( first) ;
}
}
}
class Boy {
private int no;
private 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;
}
@Override
public String toString ( ) {
return "Boy{" +
"no=" + no +
'}' ;
}
}