约瑟夫环的定义就不再赘述,直接上代码。
如果朋友能看完这个代码,相信你能理解接下面这个小故事。
有个人想从这个世界上消失,但是他又不想死,他想到了一个办法,他可以把另外一个人杀了,然后再用这个人的身份生活下去。(这个小故事与约瑟夫环无关)
#include <stdio.h>
#include <malloc.h>
struct node
{
int data;
struct node *next;
};
int main()
{
int n, m;
int i;
int answer[100];
int count = 0;
struct node *head, *tail, *p;
head = (struct node *)malloc(sizeof(struct node));
head->data = -1;
head->next = NULL;
scanf("%d%d", &n, &m);
if (n == 0 || m == 0)
{
free(head);
}
else
{
tail = head;
for (i = 0; i < n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->data = i + 1;
tail->next = p;
tail = p;
}
p->next = head->next;
i = 1;
node *cru = head->next;
node *nextnode;
while (1)
{
if (i == m)
{
answer[count] = cru->data;
count++;
nextnode = cru->next;
cru->data = nextnode->data;
cru->next = nextnode->next;
free(nextnode);
i = 1;
}
cru = cru->next;
i++;
if (count == n - 1)
{
break;
}
}
}
for (i = 0; i < count; i++)
{
printf("%d\t", answer[i]);
}
free(head);
return 0;
}