約瑟夫環是鏈表最經典的應用題:n 個人圍成一圈,從某人開始數 m 個,數到的人出列,剩下的人重新繼續數,最後留下來的即為答案。用循環鏈表來解,最直覺的做法是「以尾指標辨識整個環」——只要記住尾巴,tail->next 就是頭。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int payload;
struct node* next;
} node;
/* 在約瑟夫環尾部插入一個節點
* param : node* tail 環的尾節點
* return: node* 新的尾節點
*/
node* add(node* tail) {
if (tail == NULL) {
tail = (node*) malloc(sizeof(node));
tail->next = tail; // 只有一個節點時,自己指向自己
return tail;
} else {
node* new_tail = (node*) malloc(sizeof(node));
new_tail->next = tail->next; // 新節點接上原本的頭
tail->next = new_tail; // 舊尾接上新節點
return new_tail;
}
}
單節點時務必讓 next 指向自己,這是整個環能成立的基礎,少了這行後續的遍歷與刪除都會失控。
/* 遍歷約瑟夫環
* param : node* tail
* return: void
*/
void traverse_joseph_circle(node* tail) {
node* move = tail;
// 思路:先斷開「尾到头」的連結 conceptually,從頭節點開始往下走,
// 走到尾巴時停止。
while (move != NULL) {
move = move->next; // 先移動到頭節點
printf("%d ;", move->payload);
if (move == tail) break; // 回到尾巴就結束
}
printf("\n");
}
/* 約瑟夫環問題的實作
* param : node* tail; int step
* return: void
*/
void eliminate(node* tail, int step) {
node* move = tail;
node* save_previous = tail;
int count = 0;
while (NULL != tail && (move != move->next)) { // 只剩一個節點時結束
save_previous = move;
move = move->next;
if (++count == step) {
save_previous->next = move->next; // 跳過被刪除的節點
printf("當前要刪節點:%d\n", move->payload);
if (tail == move) tail = save_previous; // 若刪的是尾,更新尾指標
free(move);
printf("當前節點:\n");
traverse_joseph_circle(tail);
move = save_previous; // 回到上一個位置重新開始數
count = 0;
}
}
}
單向鏈表刪節點的關鍵是「必須握有前驅」,所以這裡用 save_previous 追著走。另外別忘了那個 if (tail == move)——如果刪掉的正好是尾節點而沒更新 tail,下一次遍歷就會讀到已 free 的記憶體。
int main() {
node* tail;
int i;
// 建立 20 個節點的約瑟夫環
for (i = 0; i < 20; i++) {
tail = add(tail);
tail->payload = i;
}
traverse_joseph_circle(tail);
eliminate(tail, 3);
}
0 ;1 ;2 ;3 ;4 ;5 ;6 ;7 ;8 ;9 ; 當前要刪節點:2 當前節點: 0 ;1 ;3 ;4 ;5 ;6 ;7 ;8 ;9 ; 當前要刪節點:5 當前節點: 0 ;1 ;3 ;4 ;6 ;7 ;8 ;9 ; 當前要刪節點:8 當前節點: 0 ;1 ;3 ;4 ;6 ;7 ;9 ; 當前要刪節點:1 當前節點: 0 ;3 ;4 ;6 ;7 ;9 ; 當前要刪節點:6 當前節點: 0 ;3 ;4 ;7 ;9 ; 當前要刪節點:0 當前節點: 3 ;4 ;7 ;9 ; 當前要刪節點:7 當前節點: 3 ;4 ;9 ; 當前要刪節點:4 當前節點: 3 ;9 ; 當前要刪節點:9 當前節點: 3 ;
最後留下 3。實作上有個小 bug 值得注意:main 裡的 node* tail 未初始化就傳進 add(),嚴格來說是未定義行為,正式程式碼應寫成 node* tail = NULL;。另外 eliminate 的 tail 是「傳值」,函式內部對 tail 的更新不會反映到呼叫端,若要在函式外繼續使用環,參數應改成 node** 。