单项循环链表(Java)

可以用单项循环链表来解决约瑟夫问题。

 

 

 代码实现:

ublic class Josepfu {
    public static void main(String[] args) {

        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(5);
        circleSingleLinkedList.show();
        circleSingleLinkedList.Josepfu();
    }
}
class CircleSingleLinkedList {
    private Boy first = new Boy(-1);

    public void addBoy(int nums) {
        if (nums < 1) {
            System.out.println("nums的值不正确");
            return;
        }
        Boy curBoy = first;
        for (int i = 1; i <= nums; i++) {
            if (i == 1) {
                first.setNo(i);
                curBoy.setNext(first);
            } else {
                Boy boy = new Boy(i);
                curBoy.setNext(boy);
                curBoy = boy;
                curBoy.setNext(first);
            }
        }
    }

    public void show() {
        if (first == null) {
            System.out.println("链表为空");
            return;
        }
        //辅助指针
        Boy curBoy = first;
        while (true) {
            System.out.println("编号为" + curBoy.getNo());
            if (curBoy.getNext() == first)
                break;
            curBoy = curBoy.getNext();
        }
    }

    public void Josepfu() {
        int m = 1;
        int n = 2;
        Scanner scanner = new Scanner(System.in);
        //System.out.println("请输入开始报数的小孩编号");
        //m = scanner.nextInt();
        //System.out.println("请输入出列序号");
        //n = scanner.nextInt();
        Boy curBoy = first;
        while (true) {
            curBoy = curBoy.getNext();
            if(curBoy.getNext() == first) {
                break;
            }
        }
        while (true) {
            if(curBoy.getNext() == curBoy) {
                break;
            }
            for (int i = 0; i < n - 1; i++) {
                curBoy = curBoy.getNext();
            }
            System.out.println("序号是"+curBoy.getNext().getNo());
            curBoy.setNext(curBoy.getNext().getNext());
        }
        System.out.println("最后一个是"+curBoy.getNo());
    }
}

    class Boy {
        private int no;
        private Boy next;

        public int getNo() {
            return no;
        }

        public void setNo(int no) {
            this.no = no;
        }

        public Boy getNext() {
            return next;
        }

        public void setNext(Boy next) {
            this.next = next;
        }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值