编程语言
首页 > 编程语言> > 数据结构与算法(四)循环链表解决约瑟夫问题

数据结构与算法(四)循环链表解决约瑟夫问题

作者:互联网

编号为 1-N 的 N 个士兵围坐在一起形成一个圆圈,从编号为 1 的士兵开始依次报数(1,2,3…这样依次报),数到 m 的 士兵会被杀死出列,之后的士兵再从 1 开始报数。直到最后剩下一士兵,求这个士兵的编号。

public class JosephusProblem {


    public static void main(String[] args) {
        int n = 5;
        int m = 2;
        solution(n, m);
    }

    private static void solution(int n, int m) {

        if(n < 1 || m < 1){
            System.out.println("The number of Soldiers and report must large than 0");
            return;
        }

        //create circle list
        Soldier first = new Soldier(1);
        first.next = first;
        Soldier cur = first;
        for (int i = 2; i <= n; i++) {
            Soldier temp = new Soldier(i);
            cur.next = temp;
            temp.next = first;
            cur = cur.next;
        }

        printAll(first);

        Soldier previous = cur;//the previous of reporting soldier
        Soldier current = first;//the reporting soldier
        while (previous != current){
            for (int i = 0; i < m - 1; i++) {
                current = current.next;
                previous = previous.next;
            }
            //kill the current soldier
            System.out.println("Killing soldier " + current.id);
            current = current.next;
            previous.next = current;
        }

        System.out.printf("Soldier %d Survives", current.id);

    }

    private static void printAll(Soldier first) {
        Soldier cur = first;
        while (cur.next != first){
            System.out.println("Soldier id is " + cur.id);
            cur = cur.next;
        }
        System.out.println("Soldier id is " + cur.id);
    }


    static class Soldier{
        int id;
        Soldier next;

        public Soldier(int id) {
            this.id = id;
        }
    }

}

标签:约瑟夫,cur,current,next,链表,Soldier,数据结构,id,first
来源: https://blog.csdn.net/xxz753951/article/details/114406169