Java 求解约瑟夫环问题

无意中看到这个约瑟夫环问题问题,觉得挺有意思的,然后用Java编程求解一下。

题目要求:

n个人围成一圈,从第一个人开始报数,数到K的人出局,然后从下一个人接着报数,直到最后一个人,求最后一个人的编号,或者计算出出圈顺序。

解法一:

public class Josephus {
   
	/*
	 * "约瑟夫环"问题的解决方法1
	 * 共N个人,从第S个人开始报数,报数1—M
	 * 这里初始化的13个,人从第3个开始报数,数到5的出局
	 * 最后运行结果:7 12 4 10 3 11 6 2 1 5 9 13 8
	 */
	public static void main(String args[]) {
   
		final int N=13,S=3,M=5;
		int i = S-1, k = N, g = 1, j;
		int a[] = new int[N
约瑟夫环问题是一个经典的问题,可以使用双向循环链表来解决。具体的思路可以按照以下步骤来实现1. 创建一个双向循环链表,并添加指定数量的节点 2. 定义一个计数器,用于计数当前报数数 3. 从链表的头部开始遍历,每次遍历到一个节点时,计数器加1,如果计数器的值等于指定的报数值,就将该节点从链表中删除,并将计数器重置为1 4. 当链表中只剩下一个节点时,即为最后的获胜者 下面是一个 Java 实现的示例代码: ```java public class JosephCircle { // 定义双向链表节点 private static class Node<T> { T item; Node<T> prev; Node<T> next; Node(T item, Node<T> prev, Node<T> next) { this.item = item; this.prev = prev; this.next = next; } } public static void main(String[] args) { int n = 7; // 总数 int m = 3; // 报数值 Node<Integer> head = null; Node<Integer> tail = null; // 创建双向链表 for (int i = 1; i <= n; i++) { if (head == null) { head = new Node<>(i, null, null); tail = head; head.prev = tail; tail.next = head; } else { Node<Integer> node = new Node<>(i, tail, head); tail.next = node; tail = node; head.prev = tail; } } // 从头节点开始遍历链表 Node<Integer> current = head; int count = 1; while (current.next != current) { count++; if (count == m) { count = 1; System.out.println("删除节点:" + current.item); current.prev.next = current.next; current.next.prev = current.prev; current = current.next; } else { current = current.next; } } System.out.println("获胜者:" + current.item); } } ``` 输出结果: ``` 删除节点:3 删除节点:6 删除节点:2 删除节点:7 删除节点:5 删除节点:1 获胜者:4 ``` 以上就是使用 Java 双向循环链表求解约瑟夫环问题的示例代码。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值