约瑟夫(Josephus)问题

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

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

struct Node
{
	PtrToNode Previous;
	PtrToNode Next;
	int Element;
};

Position Delete(Position P)  
{
	Position tmp;
	tmp = P->Next;
	P->Previous->Next = tmp;
	tmp->Previous = P->Previous;
	free(P);
	return tmp;
}

Position CreatDoubleList()
{
	PtrToNode head,last,now;
	head = last = malloc(sizeof(struct Node));
	now = malloc(sizeof(struct Node));
	last->Element = -1;
	head->Element = -1;
	scanf("%d",&now->Element);
	while(now->Element != 0)
	{
		last->Next = now;
		now->Previous = last;
		last = now;
		now = malloc(sizeof(struct Node));
		scanf("%d",&now->Element);
	}
	last->Next = head;
	head->Previous = last;
	free(now);
	return head;
}
 
void Josephus(List L,int m,int n)
{
	int i,count = 0;
	Position P;
	P = L->Next;
	while(n > 1)
	{
		count = m % n;
		for(i = 0;i < count;i++)
		{	
			P = P->Next;
			if(P->Element == -1)
				P = P->Next;
		} 
		printf("%d\n",P->Element);
		P = Delete(P);
		n--;
	}
	if(P->Element == -1)
	{
		P = P->Next;
		printf("%d\n",P->Element);
	}
	else
		printf("%d\n",P->Element);
}

int main()
{
	int m,n,i;
	List L;
	L = CreatDoubleList();
	scanf("%d%d",&m,&n);
	Josephus(L,m,n);

	return 0;
}

这题解得甚不合我意,答案应该是对的,有时间再想想



博客园,双向链表解决的

循环链表--解决Josephus问题


C++实现的,用双链表解决约瑟夫问题

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值