約瑟夫問題是個有名的問題:N個人圍成一圈,從第一個開始報數,第M個將被殺掉,最後剩下一個,其余人都將被殺掉。例如N=6,M=5,被殺掉的人的序號為5,4,6,2,3。最後剩下1號。
#include <stdio.h> #include <stdlib.h> #include "declear.h" typedef struct Node { ElemType data; struct Node *next; }Node, *CycLinkList; void JOSEPHUS(int totalNum, int startNum, int interval) { int index; CycLinkList node; CycLinkList temPtr; CycLinkList temPriorPtr; /*建立一個無頭結點的循環鏈表*/ CycLinkList L = (CycLinkList)malloc(sizeof(Node)); L->data = 1; L->next = L; temPtr = L; for (index = 2; index <= totalNum; index++) { node = (CycLinkList)malloc(sizeof(Node)); node->data = index; temPtr->next = node; node->next = L; temPtr = node; } temPtr = L; /*找到起始位置*/ for (index = 1; index < startNum; index++) { temPriorPtr = temPtr; temPtr = temPtr->next; } while (temPtr != temPtr->next) { /*從起始位置開始找到報數為interval的位置*/ for (index = 1; index < interval; index++) { temPriorPtr = temPtr; temPtr = temPtr->next; } printf("%d\n",temPtr->data); /*從循環鏈表中刪除該點*/ temPriorPtr->next = temPtr->next; free(temPtr); /*更新起始位置*/ temPtr = temPriorPtr->next; } } int main() { JOSEPHUS(9,2,4); return 0; }