C 约瑟夫环

本文介绍了一个基于C语言实现的约瑟夫环问题解决方案。通过创建循环链表来模拟约瑟夫环,并实现了从指定位置开始计数,每数到特定数值就移除一个节点的过程,直至链表为空。该程序详细展示了约瑟夫环问题的基本算法思路及其实现细节。

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

步骤:

1、生成循环链表

2、定位到需要删除的节点(nowNode),并记录上一个节点(preNode)

3、确保链表长度不为零。根据步长,计算删除节点位置。删除前保存下一个节点(nexNode)

4、恢复链表,跳到3。

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define NUM 10  //节点数

typedef struct student
{
	int data;
	struct student* next;
}Node;

// 约瑟夫环, 从k开始数,数到m出链表,m+1继续,直到所有出
Node* JOSEPHUS(int k, int m)
{
	/* 循环链表创立 */
	Node* head = (Node*)malloc(sizeof(Node));
	if (NULL == head)
	{
		printf("The head can't be created.\n");
		exit(1);
	}
	head -> next = head;
	head -> data = 0;

	Node* curr = head;
	for (int i = 1; i < NUM; i++)
	{
		Node* newNode = (Node*)malloc(sizeof(Node));
		if (NULL == newNode) exit(1);

		newNode -> data = i;
		newNode -> next = head;
		curr -> next = newNode;
		curr = newNode;
	}

	/* 根据k值定位到开始 */
	Node* preNode = curr;  //k-1位置节点
	Node* nowNode = head;  //k  位置节点
	while (k--) 
	{
		preNode = preNode -> next;
		nowNode = nowNode -> next;
	}
	
	/* 删除节点 */
	int num = NUM;
	while (num--)
	{
		int stepLen = m;  //步长
		Node* nexNode = NULL;
		while (stepLen--)
		{
			preNode = preNode -> next;
			nowNode = nowNode -> next;
		}
		printf("%d->", nowNode->data);
		nexNode = nowNode -> next;  //删除当前节点前,保存后节点位置
		free(nowNode);

		// 删除之后恢复链表状态
		preNode -> next = nexNode;
		nowNode = nexNode;
	}
	
	return head;
}

int main(void)
{
	Node* head = JOSEPHUS(2, 3);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值