约瑟夫环算法

liubo_24020209 liubo_24020209 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
类似于以下问题可以用约瑟夫环的算法来解决:
例:用户输入M,N值,从1至N开始顺序循环数数,每数到M输出该数值(这个值在以后的循环中不再数到),直至说有数据全部输出。

#include <stdio.h>
#include <malloc.h>

typedef struct Node
{
int index;
struct Node *next;
}JosephuNode;

int Josephu(int n, int m)
{
int i, j;
JosephuNode *head, *tail;

head = tail = (JosephuNode *)malloc(sizeof(JosephuNode));

for (i = 1; i < n; ++i)
{
tail->index = i;
tail->next = (JosephuNode *)malloc(sizeof(JosephuNode));
tail = tail->next;
}

tail->index = i;
tail->next = head;

for (i = 1; tail != head; ++i)
{
for (j = 1; j < m; ++j)
{
tail = head;
head = head->next;
}

tail->next = head->next;
printf("第%4d个出局的人是:%4d号\n", i, head->index);
free(head);
head = tail->next;
}

i = head->index;
free(head);
return i;
}

int main()
{
int n, m;

scanf("%d%d", &n, &m);
printf("最后胜利的是%d号!\n", Josephu(n, m));
//system("pause");

return 0;
}
...全文
评论 10
收藏 已收藏
分享
返回顶部
liubo_24020209
C语言 70,040 成员 243,237 内容