约瑟夫环问题(Josephus)

【问题描述】

 约瑟夫环问题(Josephus)
      用户输入M,N值,从1至N开始顺序循环数数,每数到M输出该数值,直至全部输出。写出C程序。(约瑟夫环问题 Josephus)

【解题思路】

构建一个循环链表,每个结点的编号为1,2,......,n。每次从当前位置向前移动m-1步,然后删除这个结点。

【C程序代码】

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
	int num;
	struct node *next;
}node;

node *create_list(int n)
{
	int i;
	node *head;
	node *p_cur, *p_pre;
	head = (node *)malloc(sizeof(node));
	head->num = 1;
	head->next = NULL;
	p_pre = head;
	for(i = 2; i <= n; i++)
	{
		p_cur = (node *)malloc(sizeof(node));
		p_cur->num = i;
		p_pre->next = p_cur;
		p_pre = p_cur;
	}
	p_cur->next = head;
	return head;
}

void print_list(node* head)
{
	node *p;
	printf("%d ", head->num);
	p = head->next;
	while(p != head)
	{
		printf("%d ", p->num);
		p = p->next;
	}
}

void josephus(node *head, int m)
{
	node *p_cur, *p_pre;
	int count;
	count = 1;
	p_cur = p_pre = head;
	while(1)
	{
		if(count == m)
		{
			p_pre->next = p_cur->next;
			printf("%d ", p_cur->num);
			free(p_cur);
			p_cur = p_pre->next;
			count = 1;
		}
		p_pre = p_cur;
		p_cur = p_cur->next;
		if(p_pre == p_cur)
		{
			printf("%d ", p_pre->num);
			free(p_pre);
			break;
		}
		count++;
	}
}

int main(void)
{
	node *head;
	head = create_list(5);
	print_list(head);
	printf("\n");
	josephus(head, 2);
	printf("\n");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值