其他分享
首页 > 其他分享> > 环形链表解决约瑟夫问题

环形链表解决约瑟夫问题

作者:互联网

public class CircularKinkedListDemo {
    //测试
    public static void main(String[] args) {
        CircularKinkedList circularKinkedList = new CircularKinkedList();
        circularKinkedList.countBoy(1, 10, 3);
    }

}

//定义链表
class CircularKinkedList {
    private Children first = null; //定义头指针,指向环形链表头部


    public void add(int nums) {

        if (nums < 1) {
            System.out.println("参数不合法");
            return;
        }

        Children temp = null; //中间变量
        for (int i = 1; i <= nums; i++) {
            Children children = new Children(i);
            if (i == 1) {  //第一个元素,头指针指向自己形成环
                first = children;
                first.setNext(first);
                temp = first;  //头指针不能动,用中间变量记录
            } else { //将节点插入
                temp.setNext(children);
                children.setNext(first);
                temp = children;
            }
        }
    }

    //遍历链表
    public void showBoy() {
        if (first == null) {
            System.out.println("空的");
            return;
        }
        Children temp = first; //从头开始
        while (true) {
            System.out.println(temp);
            temp = temp.getNext();
            if (temp == first) { //再一次到达头链表遍历结束
                break;
            }
        }
    }

    //约瑟夫问题
    public void countBoy(int startIndex, int muns, int num) {
        if (startIndex < 1 || muns < 1 || num < 1) {
            System.out.println("参数不合法");
            return;
        }
        add(muns); //创建链表
        Children temp = first; //中间变量用来上一个位置
        while (true){  //初始化temp位置
            temp = temp.getNext();
            if (temp.getNext() == first) {
                break;
            }
        }
        //遍历叫号
        while (true) {
            for (int i = 0; i < num - 1; i++) { //移动节点
                temp = first;
                first = first.getNext();
            }
            System.out.println(first);  //当前被叫到的节点
            temp.setNext(first.getNext());
            first = first.getNext();

            if (first.getNext() == first) { //直到自己指向自己结束
                System.out.println(first);
                break;
            }
        }

    }
}

//定义节点
class Children {
    private int no;
    private Children next = null;

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

    public int getNo() {
        return no;
    }

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

    public Children getNext() {
        return next;
    }

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

    @Override
    public String toString() {
        return "编号" + no;
    }
}

标签:circularKinkedList,int,环形,约瑟夫,链表,CircularKinkedList,null,public
来源: https://www.cnblogs.com/lucfox/p/16524704.html