(五)Java数据结构之循环链表解决约瑟夫(Josephus)环问题

package top.baikunlong.linkedlist;

/**
 * @author baikunlong
 * @date 2020/10/9 13:22
 */
public class Josephus {
    public static void main(String[] args) {
        CircleSingleLinkedList list = new CircleSingleLinkedList();
        list.countBoy(5,1,2);//2 4 1 5 3
        System.out.println();
        list.countBoy(5,2,3);//4 2 1 3 5
    }
}

/**
 * 循环单链表
 */
class CircleSingleLinkedList{
    private Boy first;
    public void addBoy(int count){
        if(count<1){
            System.out.println("最小1");
            return;
        }
        Boy temp=null;
        for (int i = 1; i <= count; i++) {
            Boy boy = new Boy(i, "boy" + i);
            if(i==1){//如果是第一个,则赋值给first,让它初始化
                first = boy;
                first.next=first;//形成环
                temp=first;//临时变量,用于移动指针进行添加
            }else {
                temp.next= boy;//下一个指向最新的boy
                boy.next=first;//最新的boy的下一个指向first形成环
                temp=boy;
            }
        }
    }
    public void show(){
        if(first==null){
            System.out.println("空链表");
            return;
        }
        Boy temp=first;
        while(true){
            System.out.println(temp.toString());
            temp=temp.next;
            if(temp==first)return;
        }
    }

    /**
     * 报数
     * @param n 总共几个人
     * @param k 从第几个开始报数
     * @param m 数几下
     */
    public void countBoy(int n,int k,int m){
        if(k>n||k<1||m<1){
            System.out.println("数据错误");
            return;
        }
        //重新初始化链表
        addBoy(n);

        //因为是单链表,所以首先需要一个临时指针指向first的前一个,帮助出圈
        Boy temp=first;
        while (true){
            if(temp.next==first){
                break;
            }else {
                temp=temp.next;
            }
        }

        //从第几个开始报数,需要移动指针到开始位置
        for (int i = 0; i < k-1; i++) {
            first=first.next;
            temp=temp.next;
        }

        //开始报数
        while (temp!=first){
            //移动m-1次,从1开始数的
            for (int i = 0; i < m - 1; i++) {
                first=first.next;
                temp=temp.next;
            }
            //删除
            System.out.println("出圈="+first.toString());
            first=first.next;
            temp.next=first;
        }
        System.out.println("最后的boy="+first.toString());
    }
}
class Boy{
    public int no;
    public String name;
    public Boy next;

    public Boy(int no,String name) {
        this.no = no;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Boy{" +
                "no=" + no +
                ", name='" + name + '\'' +
                '}';
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值