用Java實現(xiàn)約瑟夫環(huán)
作者:tanlan
約瑟夫環(huán)是一個數(shù)學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數(shù),數(shù)到m的那個人出列;他的下一個人又從1開始報數(shù),數(shù)到m的那個人又出列;依此規(guī)律重復下去,直到圓桌周圍的人全部出列。
什么是約瑟夫環(huán)呢?
約瑟夫環(huán)是一個數(shù)學的應用問題:已知n個人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報數(shù),數(shù)到m的那個人出列;他的下一個人又從1開始報數(shù),數(shù)到m的那個人又出列;依此規(guī)律重復下去,直到圓桌周圍的人全部出列。
我們用程序說話,實現(xiàn)約瑟夫環(huán)
- import java.util.Scanner;
- public class Josephus {
- private static class Node {
- public int no;// 編號
- public Node next;// 下一個節(jié)點
- public Node(int no) {
- this.no = no;
- }
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.print("請輸入總人數(shù):");
- int totalNum = scanner.nextInt();
- System.out.print("請輸入報數(shù)的大?。?quot;);
- 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;
- // 初始化環(huán)形鏈表結束
- 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);
- }
- }
原文鏈接:http://tanlan.iteye.com/blog/1159502
責任編輯:艾婧
來源:
tanlan的博客