約瑟夫環的一種實現 – JAVA編程語言程序開發技術文章

Java代碼 
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("請輸入總人數:"); 
        int totalNum = scanner.nextInt(); 
        System.out.print("請輸入報數的大小:"); 
        int cycleNum = scanner.nextInt(); 
        Node header = new Node(1); 
        Node pointer = header; 
        for (int i = 2; i <= totalNum; i++) { 
            pointer.next = new Node(i); 
            pointer = pointer.next; 
        } 
        pointer.next = header; 
        // 初始化環形鏈表結束 
        System.out.println("以下是出列的順序:"); 
        while (pointer != pointer.next) { 
            for (int i = 1; i < cycleNum; i++) { 
                pointer = pointer.next; 
            } 
            System.out.println(pointer.next.no); 
            pointer.next = pointer.next.next; 
        } 
        System.out.println(pointer.next.no); 
    } 
}

 

本文出自“像風一樣自由”
 

發佈留言