单向循环链表--约瑟夫环

写个约瑟夫环,检验一下自己的学习状况.............................
#include <stdio.h>

#define ElemType int 

typedef struct LNode{
	ElemType data;
	int      num;
	struct LNode *next;
}SqList;

void InitList(SqList **L, ElemType n);
void Round(SqList *L, int m, int n);

int main()
{
	SqList *L;
	int n, m;
	printf("the first number m:\n");
	scanf("%d", &m);
	printf("the number of students:\n");
	scanf("%d", &n);
	InitList(&L, n);
	Round(L, m, n);
	free(L);
	return 0;
}

void InitList(SqList **L, ElemType n)//建立循环链表
{
	SqList *s, *r;
	int i;
	ElemType a;
	*L = (SqList *)malloc(sizeof(SqList));
	r = *L;
	scanf("%d", &a);
	(*L)->num = 1;
	(*L)->data = a;

	for (i = 1; i < n; i++)//使用尾插法
	{
		s = (SqList*)malloc(sizeof(SqList));
		scanf("%d", &a);
		s->data = a;
		s->num  = i + 1;
		r->next = s;
		r = s;
	}
	r->next = *L;
}


void Round(SqList *L, int m, int n)
{
	int still = n;//still 里面存的是还有多少人
	int count = 1;
	while (still != 0)
	{
			
		if (m == 1)//处理密码是1的情况
		{
			printf("%d\n",L->num);
			m = L->data;
			L->data = L->next->data;
			L->num  = L->next->num;
			L->next = L->next->next;
			count = 1;
			still--;
			continue;
		}
	
		else if (count == m - 1)//报到了的话
		{
			printf("%d\n", L->next->num);//打印出列的数
			m = L->next->data;//报的数要进行变化
			L->next = L->next->next;//删除节点(注意这里应该是放在最后面来进行的)
			still--;//总共参与的人数要相应的减少1
			count = 1;//重新开始计数
			L = L->next;
			continue;
		}

		else
		{
			count++;
			L = L->next;
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值