JAVA环形链表实现约瑟夫杯问题

public class Josepfu {

    public static void main(String[] args) {


        CircleSingleLinkedList linkedList=new CircleSingleLinkedList();
        linkedList.addCircleList(10);
        linkedList.list();
        linkedList.countBoy(1,2,10);
    }

}
class CircleSingleLinkedList{
    //创建一个first节点 当前没有编号
    private Boy first = null;

    /**
     *
     * @param startNo  表示开始从哪里数
     * @param countNum  表示一次数几下
     * @param nums  最初有多少个节点在圈中
     */
    public void countBoy(int startNo,int countNum,int nums){
        if (first == null || startNo>nums || startNo<1){
            System.out.println("输入数据有错误");
            return;
        }
        Boy temp = first;
        //循环让temp指向first的前一个节点,即最后一个节点
        while (true){
            if (temp.getNext()==first){
                break;
            }
            temp=temp.getNext();
        }
        //让first指针移动到开始报数的人,temp跟在后面移动
        for (int i=1;i<startNo;i++){
            first = first.getNext();
            temp=temp.getNext();
        }
        while (true){
            //temp=first时表示圈中仅剩一人
            if (temp== first){
                break;
            }
            //让first和temp指针同时移动多少次
            for (int j=0;j<countNum-1;j++){
                first=first.getNext();
                temp=temp.getNext();
            }
            System.out.println("小孩出圈"+first.getId());
            //得到出圈的节点  然后删除该节点
            first = first.getNext();
            temp.setNext(first);
        }
        System.out.println("最后出圈节点"+first.getId());
    }

    //添加节点
    public void addCircleList(int size){
        if (size <1){
            System.out.println("人数太少 无法创建");
        }
        Boy temp = null;
        for (int i=1;i<=size;i++){
            Boy boy=new Boy(i);
            if (i == 1){
                first = boy;
                first.setNext(first);
                temp=boy;
            }else {
                temp.setNext(boy);
                boy.setNext(first);
                temp=boy;
            }
        }
    }

    public void list(){
        if (first ==null){
            System.out.println("无节点");
        }
        Boy temp =first;
        while (temp!=null){
            if (temp.getNext() == first){
                break;
            }
            System.out.println("第"+temp.getId());
            temp=temp.getNext();
        }
    }
}
class Boy{
    private int id;
    private Boy next;
    public Boy(int id){
        this.id=id;
    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Boy getNext() {
        return next;
    }

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

    @Override
    public String toString() {
        return "boy{" +
                "id=" + id +
                ", next=" + next +
                '}';
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41556688/article/details/112885172