数据结构 循环链表的应用:约瑟夫环问题

  • Post author:
  • Post category:其他


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

#define OK          1
#define ERROR       0
#define OVERFLOW    -2

typedef int ElemType;

typedef struct LNode
{
	ElemType data;
	struct LNode *next;
}LNode, *LinkList;

void Create_LinkList(LinkList &L, int n)
{
	int i = 2;
	LinkList pCur = NULL,pPrev;
	L = (LinkList)malloc(sizeof(LNode));
	if (!L)
	{
		exit(OVERFLOW);
	}
	L->data = 1;
	L->next = NULL;
	pPrev = L;
	while (--n > 0)
	{
		pCur = (LinkList)malloc(sizeof(LNode));
		if (!pCur)
		{
			exit(OVERFLOW);
		}
		pCur->data = i;
		pPrev->next = pCur;
		pPrev = pCur;
		i++;
	}
	pCur->next = L;
}

void KickFromRing(LinkList &L, int n)
{
	LinkList pCur,pPrev;
	int i = 1;
	pCur = pPrev = L;
	while (1)
	{
		if (i == n)
		{
			printf("%d\n",pCur->data);
			pPrev->next = pCur->next;
			free(pCur);
			pCur = pPrev->next;
			i = 1;
		}
		pPrev = pCur;
		pCur = pCur->next;
		if (pCur == pPrev)
		{
			printf("%d\n",pCur->data);
			free(pCur);
			break;
		}
		i++;
	}
}




int main()
{
	int m,n;
	scanf("%d%d",&m,&n);
	LinkList L;
	Create_LinkList(L,m);
	KickFromRing(L,n);
	return 0;
}



版权声明:本文为qq523176585原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。