一、Josephu约瑟夫问题

Description

约瑟夫问题:有n个人,按顺时针方向围成一圈(编号从1到n),从第1号开始报数,一直数到m,数到m的人退出圈外,剩下的人再接着从1开始报数。,编程求输入n,m后,输出出圈的序号。

Input

每行是用空格分开的两个整数,第一个是 n, 第二个是 m ( 0 < m,n <=300)。最后一行是:0 0

Output

输出出队的队列

package datastruct.josephu;

public class Josephu {
    public static void main(String[] args) {
        // 首先找到 第一个节点的前一个节点。
        Node head = new Node(1);
        head.addNode(2).addNode(3).addNode(4).addNode(5).addNode(6).addNode(7).addNode(8).next = head;
        jsephuResult(head, 8, 3);
    }

    public static void jsephuResult(Node head, int n, int m) {
        // step 1: 找到第一个节点的前一个节点
        Node temp = head;
        while (temp.next != head) {
            temp = temp.next;
        }
        while (temp.next != temp) {
            for (int i = 0; i < m - 1 && head.next != head; i++) {
                temp = temp.next;
            }
            // output and delete node
            System.out.println(temp.next.value);
            temp.next = temp.next.next;
        }
        System.out.println(temp.value);
    }
}

class Node {
    Node next = null;
    int value;

    Node(int v) {
        value = v;
    }

    Node addNode(int value) {
        Node nextNode = new Node(value);
        this.next = nextNode;
        return nextNode;
    }
}

猜你喜欢

转载自www.cnblogs.com/feihu-h/p/12641608.html