用链表实现约瑟夫环

本文介绍了一个使用C语言实现的循环链表来模拟约瑟夫环问题的解决方案。通过定义结构体来创建链表节点,并实现创建、显示及删除节点的功能。程序允许用户输入参与人数和出列位置,最终输出所有被移除的人的序号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>
struct stu{//ID用来保存序号
	int ID;
	struct stu* next;
};
struct stu*creat(struct stu *pHead,int n)//创建一个具有n个节点的循环链表
{
	struct stu *pNew,*pEnd;	
	int i=1;
	pHead=(struct stu *)malloc(sizeof(struct stu));
	pHead->ID=1;
	pEnd=pHead;
	for(i=2;i<=n;i++)
	{
		pNew=(struct stu *)malloc(sizeof(struct stu));
		pNew->ID=i;
		pEnd->next=pNew;
		pEnd=pNew; 
	}
	pEnd->next=pHead;
	return pHead;
}
void dis(struct stu*pHead)//显示链表
{
	struct stu* p=pHead;
	int i=0;
	while(p->next!=pHead)
	{
		printf("%d ",p->ID);
		p=p->next;
		i++;
		if(i%5==0)  printf("\n");
	 } 
	 printf("%d\n",p->ID);
}
struct stu* del(struct stu* p)//删除传入节点的下一个节点
{
	struct stu* temp=p->next;
	printf("%d ",p->next->ID);
	p->next=p->next->next;
	free(temp->next);
	return p->next;
}
int main()
{
	int num,place,i,j;
	printf("请输入有多少人,出列位置(>=2)");
	scanf("%d %d",&num,&place);
	struct stu*pHead,*p;
	pHead=(struct stu*)malloc(sizeof(struct stu));
	pHead=creat(pHead,num);
	dis(pHead);
	p=pHead;
	printf("删除\n"); 
	for(i=1;i<=num;i++)
	{
		for(j=2;j<place;j++)
		{
			p=p->next;
		}
		p=del(p);
		if(i%5==0)   printf("\n");
	}
 } 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值