package\u0020package2;\nimport\u0020java.util.Scanner;\nclass\u0020Node\n{\n\u0020\u0020int\u0020data;\n\u0020\u0020Node\u0020next;\n\n\u0020\u0020Node(int\u0020data)\n\u0020\u0020{\n\u0020\u0020\u0020\u0020this.data\u0020=\u0020data;\n\u0020\u0020}\n}\npublic\u0020class\u0020JosephusProblem\n{\n\u0020\u0020private\u0020static\u0020Scanner\u0020scanner;\n\u0020\u0020private\u0020static\u0020int\u0020p;\n\n\u0020\u0020public\u0020static\u0020void\u0020main(String[]\u0020args)\n\u0020\u0020{\n\u0020\u0020\u0020\u0020scanner\u0020=\u0020new\u0020Scanner(System.in);\n\u0020\u0020\u0020\u0020System.out.print("请输入总人数n:");\n\u0020\u0020\u0020\u0020int\u0020n\u0020=\u0020scanner.nextInt();\n\u0020\u0020\u0020\u0020System.out.print("请输入报数m:");\n\u0020\u0020\u0020\u0020int\u0020m\u0020=\u0020scanner.nextInt();\n\u0020\u0020\u0020\u0020System.out.print("请输入最终剩余人数p:");\n\u0020\u0020\u0020\u0020setP(scanner.nextInt());\n\n\u0020\u0020\u0020\u0020Node\u0020head\u0020=\u0020createJosephusCircle(n);\n\u0020\u0020\u0020\u0020Node\u0020current\u0020=\u0020head;\n\u0020\u0020\u0020\u0020while\u0020(current.next\u0020!=\u0020current)\n\u0020\u0020\u0020\u0020{\n\u0020\u0020\u0020\u0020\u0020\u0020for\u0020(int\u0020i\u0020=\u00201; i\u0020<\u0020m\u0020-\u00201; i++)\n\u0020\u0020\u0020\u0020\u0020\u0020{\n\u0020\u0020\u0020\u0020\u0020\u0020\u0020\u0020current\u0020=\u0020current.next;\n\u0020\u0020\u0020\u0020\u0020\u0020}\n\u0020\u0020\u0020\u0020\u0020\u0020System.out.print(current.next.data\u0020+\u0020" ");\n\u0020\u0020\u0020\u0020\u0020\u0020current.next\u0020=\u0020current.next.next;\n\u0020\u0020\u0020\u0020\u0020\u0020current\u0020=\u0020current.next;\n\u0020\u0020\u0020\u0020}\n\u0020\u0020\u0020\u0020System.out.println(current.data);\n\u0020\u0020}\n\n\u0020\u0020private\u0020static\u0020Node\u0020createJosephusCircle(int\u0020n)\n\u0020\u0020{\n\u0020\u0020\u0020\u0020Node\u0020head\u0020=\u0020new\u0020Node(1);\n\u0020\u0020\u0020\u0020Node\u0020current\u0020=\u0020head;\n\u0020\u0020\u0020\u0020for\u0020(int\u0020i\u0020=\u00202; i\u0020<=\u0020n; i++)\n\u0020\u0020\u0020\u0020{\n\u0020\u0020\u0020\u0020\u0020\u0020current.next\u0020=\u0020new\u0020Node(i);\n\u0020\u0020\u0020\u0020\u0020\u0020current\u0020=\u0020current.next;\n\u0020\u0020\u0020\u0020}\n\u0020\u0020\u0020\u0020current.next\u0020=\u0020head;\n\u0020\u0020\u0020\u0020return\u0020head;\n\u0020\u0020}\n\n\u0020\u0020public\u0020static\u0020int\u0020getP()\n\u0020\u0020{\n\u0020\u0020\u0020\u0020return\u0020p;\n\u0020\u0020}\n\n\u0020\u0020public\u0020static\u0020void\u0020setP(int\u0020p)\n\u0020\u0020{\n\u0020\u0020\u0020\u0020JosephusProblem.p\u0020=\u0020p;\n\u0020\u0020}\n}\n采用什么逻辑结构为什么内容:这段代码采用的是循环链表的逻辑结构。循环链表是一种特殊的链表,其中最后一个节点的next指针指向链表的头节点,形成一个循环。在约瑟夫问题中,每个人都与下一个人相连,当报数到m时,当前节点被移除,下一个节点成为新的当前节点,直到只剩下最后p个人。通过循环链表的结构,可以方便地实现约瑟夫问题的解决。

约瑟夫问题:循环链表实现

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

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