c语言实现约瑟夫环

#include <corecrt_malloc.h>
#include <stdio.h>
constexpr auto OK = 1;
constexpr auto Error = 0;
constexpr auto True = 1;
constexpr auto False = 0;

typedef int Status;
typedef int ElemType;
//定义双链表结构体
typedef struct Temp
{
	ElemType data;			//数据
	struct Temp* Next;
}CircularLinkedList;

//初始化循环链表
Status InitLinkedList(CircularLinkedList*& list)
{
	list = (CircularLinkedList*)malloc(sizeof(Temp));
	if (!list)
	{
		return Error;
	}
	list->data = NULL;
	list->Next = list;
	return OK;
}

//传入数据
Status createLinkedList(CircularLinkedList* list, int n)
{
	if (n < 1)
		return Error;
	CircularLinkedList* node = list;
	node->data = 1;
	for (int j = 2; j <= n; j++)
	{
		CircularLinkedList* newList = (CircularLinkedList*)malloc(sizeof(Temp));
		if (!newList)
			return Error;
		newList->Next = node->Next;
		node->Next = newList;
		newList->data = j;
		node = newList;
		//printf("数据%d\n", newList->data);
	}
	return OK;
}

//约瑟夫环函数
//Input: m:每第m个人淘汰,n:总数
Status JosephRing(CircularLinkedList* list, int n, int m)
{
	if (!list)
		return Error;
	CircularLinkedList* node=NULL;
	CircularLinkedList* del = list;
	while (n > 1)
	{
		for (int i = 0; i < m - 1; i++)
		{
			node = del;
			if (!(node->Next))
			{
				return false;
			}
			del = node->Next;
		}
		//delNode = node->Next;

		//node->Next = node->Next->Next;
		if (del&&node)								//判断del和node是否空指针
		{
			node->Next = del->Next;
			printf("删除第%d个数据\n", del->data);
			//free(del);
			del = node->Next;
		}
		n--;
	}
	if  (del)
	{
			printf("剩余第%d个数据\n", del->data);
	}
	return OK;
}

void CiecleListOperate()
{
	CircularLinkedList* list;
	int X = 10, Y = 6;
	InitLinkedList(list);
	createLinkedList(list, X);
	JosephRing(list, X, Y);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值