package com.ysfh; public class Demo1 { public static void main(String[] args) { CycLink cycLink = new CycLink(); cycLink.setLen(9);//设置玩家人数 cycLink.createCycLink(); cycLink.show(); cycLink.setK(2);//从第k个玩家开始报数 cycLink.setM(2);//报到2,该玩家出局。 cycLink.play(); } } /** * 孩子结点类 */ class Child { int no; //编号 Child nextChild = null; //指向下一个孩子的引用 public Child(int no) { this.no = no; } } /** * 环形链表类 */ class CycLink { Child firstChild = null; //指向第一个孩子 Child temp = null; int len; //记录孩子个数 int k; //从哪个孩子开始数数 int m; //数到m结束 public void setLen(int len) { this.len = len; } public void setK(int k) { this.k = k; } public void setM(int m) { this.m = m; } //创建环形链表 public void createCycLink() { for (int i = 1; i <= len; i++) { Child ch = new Child(i); if (i == 1) { firstChild = ch; temp = firstChild; } else { temp.nextChild = ch; temp = ch;//temp始终指向新进来的孩子 if (i == len) { temp.nextChild = firstChild; } } } } public void play() { Child temp = firstChild; while (this.len != 1) { //1、找到第k个数数的人 for (int i = 1; i < k; i++) { temp = temp.nextChild; } //2、数到m-1就结束 for (int i = 1; i < m - 2; i++) { temp = temp.nextChild; } temp.nextChild = temp.nextChild.nextChild; //3、下一个孩子继续数数 temp = temp.nextChild; this.len--; } System.out.println("最后出圈:" + temp.no); } //输出孩子编号 public void show() { Child temp = firstChild; do { //显示孩子编号 System.out.print(temp.no + " "); temp = temp.nextChild; } while (temp != firstChild); } }测试输入:1 2 3 4 5 6 7 8 9
测试输出:1 2 3 4 5 6 7 8 9 最后出圈:1
约瑟夫环问题
最新推荐文章于 2024-10-16 16:34:42 发布