Java采用循环单链表求解约瑟夫环问题的代码实现
时间: 2024-02-10 12:44:16 浏览: 109
以下是Java实现约瑟夫环问题的代码,采用循环单链表:
```
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
public class JosephusCircle {
public static int findLastRemainingNum(int n, int m) {
Node head = new Node(0);
Node prev = head;
for (int i = 1; i < n; i++) {
Node curr = new Node(i);
prev.next = curr;
prev = curr;
}
prev.next = head;
Node curr = head;
while (curr.next != curr) {
for (int i = 1; i < m - 1; i++) {
curr = curr.next;
}
curr.next = curr.next.next;
curr = curr.next;
}
return curr.val;
}
}
```
该算法的时间复杂度为 O(n * m),其中 n 为链表长度,m 为报数的步长。
阅读全文