/*分析,这里我偷了个懒,因为题中没有说必须要删除结点,我们只用得出最后一个人的编号就好了,所以可以
先给每个结构体定义一个用来报数的,初始为1,报到3就为0,最后剩下一个的时候就输出
主要看写的Shu函数,其他的就是正常的链表创建输出释放的流程
*/
#include<stdio.h>
#include<stdlib.h>
#define P 10
#define LEN sizeof(struct People)
struct People *Create(int n);
void Print(struct People *head);//测试链表是否创建成功
void Shu(struct People *head); //主要看这个函数,其他的都差不多
void Fang(struct People *head);
struct People
{
int bian;
int shu;
struct People *next;
};
int main()
{
struct People *head;
head=Create(P);
//Print(head);
Shu(head);
Fang(head);
return 0;
}
struct People *Create(int n)
{
struct People *head=NULL,*p,*p1;
int i=0;
while(i<n)
{
p=(struct People *)malloc(LEN);
p->bian =++i;
p->shu =1;
p->next =NULL;
if(head==NULL)
{
head=p;
p1=p;
p=p->next ;
}
else
{
p1->next =p;
p1=p;
p=p->next ;
}
}
return head;
}
void Print(struct People *head)
{
struct People *p;
p=head;
while(p!=NULL)
{
printf("%d,%d\n",p->bian ,p->shu );
p=p->next ;
}
putchar('\n');
}
void Shu(struct People *head)
{
struct People *p;
p=head;
int i=P,j=1; //先定义i为总人数,j报数
while(i>1) //一直循环报数直到只剩下一个人
{
if(p->shu !=0) //也就是没有报到过3的人继续报数
{
p->shu =j;
j++;
if(j>3)
j=1;
if(p->shu ==3)//如果报到数为3,就让他的数为0,意思就是退出之后的报数,并且人数减少一个
{
p->shu =0;
i--;
}
}
p=p->next ;
if(p==NULL) //如果到了链表尾部剩下的人还超过一个,就又从链表头开始依次报数
{
if(i>1)
p=head;
}
}
p=head; //从链表头开始,没有报到过3的输出他的编号
while(p!=NULL)
{
if(p->shu !=0)
printf("最后一个人编号为:%d\n",p->bian);
p=p->next ;
}
}
void Fang(struct People *head)
{
struct People *p;
while(head!=NULL)
{
p=head;
head=head->next ;
free(p);
}
head=NULL;
}
11-29
4万+
11-23
980
03-31
1999