约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3…n分别表示)围坐在一张圆桌周围。从编号为1的人开始报数,数到m的那个人出列;
void JosephCycle(pList * pplist, int num)
{
assert(pplist);
pNode cur = NULL;
pNode del = NULL;
int count = 0;
cur = *pplist;
while (cur->next)
{
cur = cur->next;
}
cur->next = *pplist;
cur = *pplist;
while (cur->next != cur)
{
count = num;
while (--count)
{
cur = cur->next;
}
printf("删除:%d\n", cur->data);
del = cur->next;
cur->data = del->data;
cur->next = del->next;
free(del);
del = NULL;
}
cur->next = NULL;
}
void TestJosephCycle()
{
Node* plist = NULL;//指向第一个节点的指针
pNode pos = NULL;
PushBack(&plist, 1);
PushBack(&plist, 2);
PushBack(&plist, 3);
PushBack(&plist, 4);
PushBack(&plist, 5);
PrintLinkList(plist);
JosephCycle(&plist, 3);
}
运行结果为: