新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
用Java實(shí)現(xiàn)約瑟夫環(huán)
什么是約瑟夫環(huán)呢?

約瑟夫環(huán)是一個(gè)數(shù)學(xué)的應(yīng)用問題:已知n個(gè)人(以編號1,2,3...n分別表示)圍坐在一張圓桌周圍。從編號為k的人開始報(bào)數(shù),數(shù)到m的那個(gè)人出列;他的下一個(gè)人又從1開始報(bào)數(shù),數(shù)到m的那個(gè)人又出列;依此規(guī)律重復(fù)下去,直到圓桌周圍的人全部出列。
我們用程序說話,實(shí)現(xiàn)約瑟夫環(huán)
- import java.util.Scanner;
- public class Josephus {
- private static class Node {
- public int no;// 編號
- public Node next;// 下一個(gè)節(jié)點(diǎn)
- public Node(int no) {
- this.no = no;
- }
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.print("請輸入總?cè)藬?shù):");
- int totalNum = scanner.nextInt();
- System.out.print("請輸入報(bào)數(shù)的大?。?);
- 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)形鏈表結(jié)束
- 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
【編輯推薦】
- Java 8整裝待發(fā) 圖謀云計(jì)算
- Java 7是蜜糖還是毒藥?
- 選用Ibatis和Hibernate的區(qū)別
- JRuby和Java 7 我們可以期待什么
- 關(guān)于Eclipse使用64位Java 7崩潰的問題
分享標(biāo)題:用Java實(shí)現(xiàn)約瑟夫環(huán)
文章路徑:http://m.fisionsoft.com.cn/article/dpdjoei.html


咨詢
建站咨詢
