//约瑟夫环
#include
#include
typedef struct node
{
int code;
int number;
struct node *next;
} Node,LinkList;
void InitList(LinkList L)
{
L=malloc(sizeof(Node));//C语言可以不用强制转换,malloc返回void
L->next=NULL;
}
void CreateList(LinkList *L)
{
Node *r,*s;
int i=1,c,n;
r=L;
printf("请输入人数n:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("请输入第%d个人的密码:",i);
scanf("%d",&c);
s=malloc(sizeof(Node));
s->code=c;
s->number=i;
r->next=s;
r=s;
}
r->next=L->next;
}
void PrintNum(LinkList *L,int m)
{
Node *pre,*r;
pre=L;
int i=1;
int flag=1;
while(flag)
{
while(i!=m)
{
pre=pre->next;
i++;
}
r=pre->next;
m=r->code;
printf("%5d",r->number);
pre->next=r->next;
free(r);
i=1;
if(pre==NULL) flag=0;//为什么不能终止循环?
}
}
int main()
{
LinkList L;
InitList(&L);
CreateList(&L);
int m;
printf("请输入上限值m:");
scanf("%d",&m);
PrintNum(&L,m);
return 0;
}
http://blog.csdn.net/IT_iverson/article/details/76615041
上面给的网址和文字混到一块了,这是正确的网址~
http://www.cnblogs.com/hubavyn/p/4438088.html
void josephcycle(PLinklist pplist, Datatype k)//约瑟夫环
{
Node *cur = pplist;
Node *del = NULL;
int count = 0;
while (1)
{
count = k;
if (cur == cur->next)//剩一个数字退出
{
break;
}
while (count-2>0)
{
cur = cur->next;
--count;
}
printf("%d ", cur->next->data);
del = cur->next;
cur->next = del->next;
cur = cur->next;
free(del);
}
printf("%d\n", cur->data);
}
这是我写的约瑟夫环你参考一下
http://blog.csdn.net/IT_iverson/article/details/76615041这是C语言链表相关面试提,感兴趣的话可以研究一下
初始化错了,L的next应该指向他自己