約瑟夫環實現:
// use C99 #include <stdio.h> #include <malloc.h> #define uint unsigned int //構建結構體 typedef struct Node { uint Num; struct Node *next; } JoseNode, *PNode, *Head; //初始化循環單鏈表 Head init_head() { Head h = (Head) malloc(sizeof(JoseNode)); if (!h) { printf("初始化鏈表錯誤!\n"); return 0; } h->next = h; return h; } //單鏈表插入操作 uint insert(PNode h, uint N) { PNode p = h, q; if (N == 1) { p->Num = 1; p->next = p; return 1; } for (int pos = 2; pos <= N; pos++) { p = p->next; q = (JoseNode *) malloc(sizeof(JoseNode)); if (!q) { return 0; } q->Num = pos; q->next = p->next; p->next = q; } return 1; } //出局函數 PNode delete(Head h, uint n, uint k) { PNode p = h, q; while (n-- > 1) { for (int i = 1; i < k - 1; i++) { p = p->next; } q = p->next; p->next = q->next; p = p->next; printf("出局的人為:%3d號\n", q->Num); free(q); } return p; } //遍歷 void print_list(Head h, uint M) { int i = 0; PNode p = h; printf("參與的人的編號為:\n"); while (i++ < M) { printf("%d ", p->Num); p = p->next; } printf("\n"); } int main() { uint n = 0;//參與的人數 uint k = 0;//報數密碼 while (n <= 1) { printf("請輸入參與人數(大於1):"); scanf("%d", &n); } while (k <= 1) { printf("請輸入出局密碼(大於1):"); scanf("%d", &k); } Head h = init_head(); insert(h, n); print_list(h, n); PNode r = delete(h, n, k); printf("\n\n獲勝者為:%3d號\n", r->Num); return 0; }
參考:https://www.cnblogs.com/deom/p/4858010.html,此處對代碼作了一定修改。