什么是約瑟夫環呢?
約瑟夫環是一個數學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數,數到m的那個人出列;他的下一個人又從1開始報數,數到m的那個人又出列;依此規律重復下去,直到圓桌周圍的人全部出列。
我們用程序說話,實現約瑟夫環:
import java.util.Scanner;
public class Josephus{
private static class Node{
public int no;//編號
public Node next;//下一個節點
public Node(int no){
this. no=no
}
}
public static void main(String[]args) {
SCanner scanner=new Scanner(System.in);
System.out.print('out. print("請輸入總人數:");
int totalNum=scanner. nextInt);
System.out.print("請輸入報數的大小:");
int cycleNum=canner. nextInt();
Node heade==new Node(1);
Node pointer=heade;
for(int i=2;i<=totalNum;i++){
pointer.next=new Node(i);
pointer=pointer.next;
}
pointer=pointer. next;
pointer. next=header;
//初始化環形鏈表結束
System.out.p:Intln("out. println("以下是出列tb的順序:‘)‘
while (pointer!,pointer. next) {
for (int i=1;:<cycleNum; i++)
pointer=pointer. next;
}
System.out.prlntln(pointer.next.no)out. println(pointer. next.no);
pointer. next=pointer. next. next;
}
System. out. println(pointer.next.no);
}
}