java约瑟夫环问题循环链表
时间: 2023-12-31 07:24:55 浏览: 98
以下是Java使用循环链表解决约瑟夫环问题的示例代码:
```java
public class JosephusProblem {
public static void main(String[] args) {
int totalPeople = 5; // 总人数
int countNum = 2; // 报数到几的人出列
// 创建循环链表
Node head = new Node(1);
Node current = head;
for (int i = 2; i <= totalPeople; i++) {
current.next = new Node(i);
current = current.next;
}
current.next = head; // 形成循环
// 开始报数并出列
Node prev = null;
while (head.next != head) {
for (int i = 1; i < countNum; i++) {
prev = head;
head = head.next;
}
prev.next = head.next;
head = prev.next;
}
// 输出最后剩下的人
System.out.println("最后剩下的人是:" + head.data);
}
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
}
```
阅读全文