约瑟夫环

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

typedef struct YueSeFuHuan
{
	int num;
	struct YueSeFuHuan *next;
	struct YueSeFuHuan *before;
}YueSeFu;

YueSeFu *Create(int allNum);
YueSeFu *FindStart(YueSeFu *pHead, int startNum);
int OutNum(YueSeFu *pStart, int allNum, int outNum);

void main()
{
	int startNum,allNum,outNum,numLeave;
	YueSeFu *pHead,*pStart;

	printf("Please input allNum,startNum,outNum: ");
	scanf("%d%d%d",&allNum,&startNum,&outNum);

	pHead = Create(allNum);  //创建一个约瑟夫环;

	pStart = FindStart(pHead, startNum);  //从环中找到开始的位置;

	numLeave = OutNum(pStart, allNum, outNum);

	printf("The leave number is %d\n",numLeave);
}

YueSeFu *Create(int allNum)
{
	YueSeFu *pHead,*pNow,*pBefore;
	int i;

	if ( allNum < 1 )  //判断是否有数据,如果没有,直接结束程序;
	{
		printf("NO NUM!\n");
		exit(1);	
	}

	for (  i=1; i<=allNum; i++ )
	{
		if ( i == 1 )
		{
			pHead = pNow = (YueSeFu * )malloc(sizeof(YueSeFu));
			if ( pHead == NULL )
			{
				exit(1);
			}
		}
		else
		{
			pNow = (YueSeFu * )malloc(sizeof(YueSeFu));
			if ( pNow == NULL )
			{
				exit(1);
			}
			pBefore->next = pNow;
			pNow->before = pBefore;
		}
		
		pNow->num = i;
		pBefore = pNow;
	}

	pNow->next = pHead;  //将最后一个结点的指针指向第一个结点,从而构成一个环;
	pHead->before = pNow;//将第一个节点的before指向最后一个节点

	return pHead;
}

YueSeFu *FindStart(YueSeFu *pHead, int startNum)
{
	YueSeFu *pNow;
	int i;

	pNow = pHead;

	for ( i=1; i<startNum; i++ )
	{
		pNow = pNow->next;
	}

	return pNow;
}

int OutNum(YueSeFu *pStart, int allNum, int outNum)
{
	YueSeFu *pNow=pStart,*pBfore,*pB;
	int i;

	i = 0;

	while ( pNow != pNow->next)
	{
		if ( i == outNum-1 )
		{
            printf("%d\n",pNow->num);
			pNow->before->next = pNow->next;
			pNow->next->before = pNow->before;
			pB = pNow->before;
			free(pNow);
			
			pNow = pB;//pNow指向被删除结点的前一个,应为if体后面便将pNow重新变为了下一个结点
			i =	-1; //i为-1是为了后面i++后就为0,与进入循环一样
		}
		pNow = pNow->next;
		i++;
	}

	return pNow->num;
}

 
阅读更多
个人分类: 每天一道算法
想对作者说点什么? 我来说一句

约瑟夫环问题的MFC简单实现

2017年11月28日 47.51MB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭