C语言------约瑟夫环(单向循环链表)

#include <stdio.h>
#include <stdlib.h>
void creat();//--->>根据人数创建结点函数
void run();//---->>运行游戏函数
int a,i,n;
struct pepole
	{
		int number;
		struct pepole *next;
	}*head,*s,*b;//--->>head为头结点,s为上一个结点,b为当前结点
int main()
{
     printf("请输入参加游戏人数:"); 
	 scanf("%d",&a);
	 creat();
	 run();
	 printf("最后获胜的是%d号",s->number);
void creat()
{
     if(a>0)
	 {
		b=(struct pepole*)malloc(sizeof(struct pepole));
		b->number=1;
		s=b;
		head=b;
		if(a>1)
		{
			for(i=2;i<=a;i++)
			{
				b=(struct pepole*)malloc(sizeof(struct pepole));
				b->number=i;
				s->next=b;
				s=b;
			}
			b->next=head;
		} 	
	}
}
void run()
{
     if(a>1)
	 {
		n=0;
		b=head;
		while(a!=1)
		{
			s=b;
			b=b->next;
			n++;
			if(n==2)
			{
				n=0;
				s->next=b->next;
				free(b);
				b=s->next;
				a--;
			}
		}
	}
}
发布了17 篇原创文章 · 获赞 30 · 访问量 1819

猜你喜欢

转载自blog.csdn.net/qq_37451250/article/details/103266712