java 约瑟夫问题

public class Test {


    public static void main(String[] args) {
        Node first = null;
        Node pre = null;

        for (int i = 1; i <= 41; i++) {
            if (i == 1) {
                first = new Node<>(i, null);
                pre = first;
                continue;
            }

            Node node = new Node(i, null);

            pre.next = node;

            pre = node;

            if (i == 41) {
                pre.next = first;

            }

        }

        Node n = first;
        Node before = null;
        int count = 0; //3.遍历链表,每循
        while (n.next != n) {

            if (count == 3) {
                before.next = n.next;
                System.out.println(n.data);
                count = 0;
                n = n.next;
            } else {
                before = n;
                n = n.next;
                count++;
            }


        }
        System.out.println(n.data);

    }


    static class Node {
        int data;
        Node next;

        public Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
}

你可能感兴趣的:(java 约瑟夫问题)