用Java實現約瑟夫環

什麼是約瑟夫環呢?java

約瑟夫環是一個數學的應用問題:已知n我的(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號爲k的人開始報數,數到m的那我的出列;他的下一我的又從1開始報數,數到m的那我的又出列;依此規律重複下去,直到圓桌周圍的人所有出列。this

咱們用程序說話,實現約瑟夫環spa

 
  1. import java.util.Scanner; 
  2.  
  3. public class Josephus { 
  4.     private static class Node { 
  5.         public int no;// 編號 
  6.         public Node next;// 下一個節點 
  7.  
  8.         public Node(int no) { 
  9.             this.no = no; 
  10.         } 
  11.     } 
  12.  
  13.     public static void main(String[] args) { 
  14.         Scanner scanner = new Scanner(System.in); 
  15.         System.out.print("請輸入總人數:"); 
  16.         int totalNum = scanner.nextInt(); 
  17.         System.out.print("請輸入報數的大小:"); 
  18.         int cycleNum = scanner.nextInt(); 
  19.         Node header = new Node(1); 
  20.         Node pointer = header; 
  21.         for (int i = 2; i <= totalNum; i++) { 
  22.             pointer.next = new Node(i); 
  23.             pointer = pointer.next; 
  24.         } 
  25.         pointer.next = header; 
  26.         // 初始化環形鏈表結束 
  27.         System.out.println("如下是出列的順序:"); 
  28.         while (pointer != pointer.next) { 
  29.             for (int i = 1; i < cycleNum; i++) { 
  30.                 pointer = pointer.next; 
  31.             } 
  32.             System.out.println(pointer.next.no); 
  33.             pointer.next = pointer.next.next; 
  34.         } 
  35.         System.out.println(pointer.next.no); 
  36.     } 
  37. }
相關文章
相關標籤/搜索