约瑟夫环问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值