数据结构之约瑟夫问题

只为解决问题,没有细致到完善像空集等的工作,如有问题,请指正,谢谢

# include 
# include 

typedef struct Node
{
	struct Node * pPrev;
	int Number;
	struct Node * pNext;
}NODE,*PNODE;

PNODE init();
void traverse(PNODE);
PNODE Kill(PNODE,int *);

int main()
{
	int number=0;
	PNODE pHead=init();
	traverse(pHead);

	while(pHead->pNext->pNext!=pHead)			//如果不为两个人时继续杀,pHead->pNext指向下一个,由于只有两个人,所以pHead->pNext->pNext指向自己
	{
		pHead=Kill(pHead->pNext->pNext,&number);	//pHead->pNext->pNext不为两个人就是杀第三人
		printf("被杀的编号为:%d\n",number);
	}
	
	printf("\n不会被杀的人是:");
	traverse(pHead);
	return 0;
}

PNODE init()
{
	PNODE pHead=(PNODE)malloc(sizeof(NODE));
	pHead->Number=1;
	pHead->pNext=pHead;
	pHead->pPrev=pHead;
	PNODE p=pHead;

	for (int i=2;i<=41;++i)						//人员编号
	{
		PNODE pNew=(PNODE)malloc(sizeof(NODE));
		pNew->Number=i;

		pNew->pNext=pHead;
		pNew->pPrev=p;

		p->pNext=pNew;
		pHead->pPrev=pNew;		
		
		p=pNew;
	}

	return pHead;
}

void traverse(PNODE pHead)
{
	PNODE p=pHead;	
	do
	{
		printf("%d ",p->Number);
		p=p->pNext;		
	}while(p!=pHead);
	
	printf("\n");
}

PNODE Kill(PNODE p,int * number)
{	
	PNODE temp=p->pNext;
	*number=p->Number;
	p->pPrev->pNext=p->pNext;
	p->pNext->pPrev=p->pPrev;
	free(p);

	return temp;
}


你可能感兴趣的:(数据结构)