约瑟夫问题(猴子选大王): n只猴子要选大王,选举办法如下:所有猴子按1,2,…,n编号围坐一圈,从第一号开始按1,2,…,m报数,凡报m号的推出圈外,如此循环报数,直到圈内剩下一只猴子时,这只猴子就是大王.n和m由键盘输入,打印出最后剩下的猴子号.
由于很多书上都有的习题,以及很多人问所以...
#include <stdio.h>
#include <malloc.h>
struct Link{
int id;
Link *next;
};
void Initialize(int n, Link *head)
{
int i;
Link *p;
for (i = 1, p = head; i <= n; i++){
p->next = (Link *) malloc (sizeof(Link));
p = p->next;
p->id = i;
}
p->next = head->next;
}
void Delete(Link *node)
{
Link *temp;
temp = node->next;
printf("%d ", node->next->id);
node->next = temp->next;
free(temp);
}
void main()
{
Link *head, *p;
int n, i, k;
printf("%s","Input n,k = ");
scanf("%d%d", &n, &k);
head = (Link *) malloc (sizeof(Link));
head->next = (Link *) malloc (sizeof(Link));
Initialize(n, head);
for (p = head, i = 1; p != p->next; p = p->next, i++){
if (i == k){
i = 1;
Delete(p);
}
}
printf("\n");
printf("%d", p->id);
}