约瑟夫环 java_约瑟夫环Java实现
/**
* 約瑟夫問題
* 設編號為 1,2,… n 的 n 個人圍坐一圈,
* 約定編號為 k(1<=k<=n)的人從 1 開始報數,
* 數到 m 的那個人出列,
* 它的下一位又從 1 開始報數,數到 m 的那個人又出列,
* 依次類推,直到所有人出列為止,
* 由此 產生一個出隊編號的序列。
*/
public class JosephuDemo {
public static void main(String[] args) {
CircleSingleLinkedList circle = new CircleSingleLinkedList();
int n = 5;
circle.build(n);
circle.show();
int[] order = circle.orderOutOfCircle(3, 2, n);
System.out.println(Arrays.toString(order));
}
}
class CircleSingleLinkedList {
private Node first;
// 構建約瑟夫環
public void build(int n) {
if (n < 1) {
System.out.println("輸入的值不正確!");
return;
}
Node cur = null; // 輔助指針,用來幫助構建環形鏈表
for (int i = 1; i <= n; i++) {
Node node = new Node(i);
if (i == 1) {
first = node;
first.next = first;
cur = first;
} else {
cur.next = node;
node.next = first;
cur = node;
}
}
}
/**
* 返回約瑟夫環問題的出環順序
* @param start 從第幾個開始數
* @param count 數幾下
* @param n 最初環中有多少個
* @return
*/
public int[] orderOutOfCircle(int start, int count, int n) {
if (first == null || start > n) throw new InvalidParameterException("參數有誤");
int[] res = new int[n];
int index = 0;
Node helper = first;
// 讓helper指向環形鏈表的最后那個node
// helper 指向了最后的node,則終止循環
while (helper.next != first) {
helper = helper.next;
}
// 小孩報數前,先讓first和helper移動start-1次
for (int i = 0; i < start - 1; i++) {
first = first.next;
helper = helper.next;
}
// 小孩報數時,讓first和helper指針同時移動count - 1次,然后出圈
// 這時說明環中只剩下一個node
while (first != helper) {
// 讓first和helper同時移動count - 1次
for (int i = 0; i < count - 1; i++) {
first = first.next;
helper = helper.next;
}
// 這時first指向的小孩就是要出圈的小孩
res[index++] = first.value;
first = first.next;
helper.next = first;
}
res[index] = first.value; // 最后留在圈中的小孩也要加入進結果
return res;
}
// 遍歷當前環形鏈表
public void show() {
if (first == null) {
System.out.println("鏈表為空");
return;
}
Node cur = first;
while (true) {
System.out.print(cur.value + " ");
if (cur.next == first) break;
cur = cur.next;
}
}
}
參考: 韓順平老師的數據結構
總結
以上是生活随笔為你收集整理的约瑟夫环 java_约瑟夫环Java实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 『AA』AutoAnchor自动猫
- 下一篇: 在线扒站复活版源码