以下是使用面向对象实现约瑟夫环问题的 Java 代码:

import java.util.ArrayList;
import java.util.List;

public class JosephusCircle {
    private List<Integer> circle;
    private int currentIndex;

    public JosephusCircle(int size) {
        circle = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            circle.add(i);
        }
        currentIndex = 0;
    }

    public int getNextPerson(int step) {
        currentIndex = (currentIndex + step - 1) % circle.size();
        return circle.remove(currentIndex);
    }

    public static void main(String[] args) {
        int size = 10;
        int step = 3;

        JosephusCircle circle = new JosephusCircle(size);

        for (int i = 0; i < size; i++) {
            int nextPerson = circle.getNextPerson(step);
            System.out.println('Person ' + nextPerson + ' is removed.');
        }
    }
}

以下是使用链表实现约瑟夫环问题的 Java 代码:

public class JosephusCircle {
    private Node head;
    private Node tail;
    private int size;

    private class Node {
        private int value;
        private Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    public JosephusCircle(int size) {
        if (size <= 0) {
            throw new IllegalArgumentException('Size must be positive.');
        }

        this.size = size;
        head = new Node(0);
        Node curr = head;

        for (int i = 1; i < size; i++) {
            curr.next = new Node(i);
            curr = curr.next;
        }

        tail = curr;
        tail.next = head;
    }

    public int getNextPerson(int step) {
        if (step <= 0) {
            throw new IllegalArgumentException('Step must be positive.');
        }

        if (size == 0) {
            throw new IllegalStateException('Circle is empty.');
        }

        for (int i = 0; i < step - 1; i++) {
            head = head.next;
            tail = tail.next;
        }

        int removedPerson = head.value;
        head = head.next;
        tail.next = head;
        size--;

        return removedPerson;
    }

    public static void main(String[] args) {
        int size = 10;
        int step = 3;

        JosephusCircle circle = new JosephusCircle(size);

        for (int i = 0; i < size; i++) {
            int nextPerson = circle.getNextPerson(step);
            System.out.println('Person ' + nextPerson + ' is removed.');
        }
    }
}

这两个实现方式都可以正确地解决约瑟夫环问题。


原文地址: https://www.cveoy.top/t/topic/picR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录