一个用链表做踢人的功能,就是约瑟夫算法,看看吧
运行了下怎么就循环了一次。有些疑惑? 求解释
#include<stdio.h>
#include<malloc.h>
#define NULL 0
struct person
{
int num;
struct person *next;
}a;
struct person *input(struct person *head) //建立链表,对人编号,由1号到13号;
{
int n=0;
struct person *p1, *p2;
p1=p2=(struct person *)malloc(sizeof(struct person));
p1=&a;
head=p1;
printf("please input the bianhao:\n");
while(++n<=13)
{
scanf("%d", &p1->num);
if(n==13)
{
p1->next=NULL;
break;
}
p2=p1;
p1=(struct person *)malloc(sizeof(struct person));
p2->next=p1;
}
return(head);
}
struct person *search(struct person *head, int n) //0表示被提出,n记录剩下的人数,当剩一人时就退出while
{
int k=1;
struct person *p;
p=head;
while(n>1)
{
if(p->num!=0)
{
k++;
p=p->next;
}
else
{
p=p->next;
}
if(k==3)
{
p->num=0;
n--;
k=1;
p=p->next;
}
if(p->next==NULL)
{
p=head;
while(p->num==0)
{
p=p->next;
}
}
}
return(head);
}
void main()
{
struct person *head=NULL, *p=NULL;
int i;
head=input(head);
p=search(head, 13);
printf("the last number is:\n");
for(i=0;i<13;i++)
{
if(p->num!=0)
{
printf("%d\n", p->num);
}
p=p->next;
}
}