约瑟夫环问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为1的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
下例实现是:n=50, m=3
#include <stdio.h>
#define nmax 50
int main()
{
int k,m,num[nmax],*p;
printf("please input the total of numbers:");
p = num;
for (int i=0; i<nmax; i++)
{
*(p+i) = i + 1;
}
k = 0;
m = 0;
int h = 0;
while (m < nmax-1)
{
if (*(p+h) != 0)
{
k++;
}
if (k == 3)
{
*(p+h) = 0;
k=0;
m++;
}
h++;
if (h == nmax)
{
h = 0;
}
}
while (*p == 0)
{
p++;
}
printf("%d is left/n", *p);
return 0;
}
这个是数组的实现方式,其实还是指针的作用。
#include <stdio.h>
#include <malloc.h>
#define N 50
#define M 3
typedef struct node *link;
struct node
{
int item;
link next;
};
link NODE(int item, link next)
{
link t = (link)malloc(sizeof(*t));
t->item = item;
t->next = next;
return t;
}
int main()
{
link t = NODE(1, NULL);
t->next = t;
for (int i=2; i<=N; i++)
{
t->next = NODE(i, t->next);
t = t->next;
}
while (t != t->next)
{
for (int i=1; i<M; i++)
{
t = t->next;
}
t->next = t->next->next;
}
printf("%d/n", t->item);
return 0;
}
这个是见一个循环链表。方式不同,但是我觉得 执行的思路还是一样的。
输出都是:11