Java解决约瑟夫问题(单向循环链表)
发布日期:2021-05-08 03:26:49 浏览次数:22 分类:精选文章

本文共 1481 字,大约阅读时间需要 4 分钟。

问题转换

41个人坐成一个圆圈,第一个人编号为1,第二个人编号为2,依此类推。编号为1的人开始从1报数,依次向后,报数到3的那个人退出圈;自退出那个人开始的下一个人再次从1开始报数,以此类推。最终退出的最后一个人的编号是多少?

解题思路

为了解决这个问题,我们可以使用循环链表来模拟报数过程。具体步骤如下:

  • 构建循环链表:包含41个节点,分别存储1到41之间的值。
  • 使用计数器:记录当前报数的值。
  • 遍历链表:每次循环时,计数器递增。
  • 判断计数器值:如果计数器为3,则删除当前节点并打印节点的值,重置计数器。
  • 重复过程:直到所有节点都退出圈。
  • 代码实现

    public class JosephTest {    public static void main(String[] args) {        // 创建循环链表        Node first = new Node(1, null);        Node pre = first;        for (int i = 2; i <= 41; i++) {            Node newNode = new Node(i, null);            pre.next = newNode;            pre = newNode;        }        pre.next = first; // 闭合循环        int count = 0;        Node current = first;        Node before = null;        while (current != before) {            count++;            if (count == 3) {                // 删除当前节点                before.next = current.next;                System.out.println(current.value + "退出");                // 重置计数器                count = 0;                // 更新current到下一个节点                current = current.next != null ? current.next : first;                before = before.next;            } else {                before = current;                current = current.next != null ? current.next : first;            }        }    }    private static class Node {        int value;        Node next;        Node(int value, Node next) {            this.value = value;            this.next = next;        }    }}

    运行结果

    最终退出的节点编号依次为16和31。通过这个过程,我们可以看出约瑟夫和他的朋友成功地避免了死亡,展示了他们的智慧和勇气。

    上一篇:ConerStone3.0.3下载地址
    下一篇:Socket通信原理和基础实践

    发表评论

    最新留言

    能坚持,总会有不一样的收获!
    [***.219.124.196]2025年04月08日 18时05分47秒