• 环形链表介绍和约瑟夫环


    clipboard

    创建一个环形链表:

    clipboard

    public class Josepfu {
        public static void main(String[] args) {
            CircleSingleLinkedList linkedList = new CircleSingleLinkedList();
            linkedList.addBody(5);
            linkedList.showBoys();
        }
    }
    
    
    
    //创建一个环形的单向链表
    class CircleSingleLinkedList{
        //创建一个first节点,当前没有编号
        private  Boy first = null;
    
    
        //添加小孩节点,构建一个环形链表
        public void addBody(int k){
            if(k<2){
                System.out.println("请添加两个及两个以上的小孩");
                return;
            }
            Boy curBoy = null;
            for(int i=1;i<=k;i++){
                Boy boy = new Boy(i);
                if(i==1){
                    first=boy;
                    first.setNext(first);
                    curBoy = boy;
                }else{
                   curBoy.setNext(boy);
                   boy.setNext(first);
                   curBoy=boy;
                }
            }
        }
    
        //遍历环形链表
        public void showBoys(){
            if(first==null){
                System.out.println("链表为空");
            }
            Boy curBoy =first;
            while(true){
                System.out.printf("小孩的编号为%d
    ",curBoy.getNo());
                if(curBoy.getNext()==first){
                    break;
                }
                curBoy= curBoy.getNext();
            }
        }
    
    }
    
    //创建一个boy类,表示一个节点
    class Boy{
        private int no;
        private Boy next;  //指向下一个节点默认为空
    
        public Boy(int no) {
            this.no = no;
        }
    
        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;
        }
    }

    约瑟夫环问题

  • 相关阅读:
    k8s-istio记录
    k8s
    单词 -(动物)
    RxJs
    .netcore 3.1 unbuntu
    单词规整
    AutoMapper
    时间
    ye
    特殊权限
  • 原文地址:https://www.cnblogs.com/houchen/p/13417306.html
Copyright © 2020-2023  润新知