/*10人围成一圈,1-10编号,依次报数,编号为1的开始报数,报道3退出,余下的继续报数,最后留下的人的编号*/

/*分析,这里我偷了个懒,因为题中没有说必须要删除结点,我们只用得出最后一个人的编号就好了,所以可以
先给每个结构体定义一个用来报数的,初始为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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值