展开全部
#include <stdio.h>
#include <stdlib.h>
typedef struct _RingNode
{
int pos;
struct _RingNode *next;
}RingNode, *RingNodePtr;
void CreateRing(RingNodePtr pHead, int count)
{
RingNodePtr pCurr = NULL, pPrev = NULL;
int i = 1;
pPrev = pHead;
while(--count > 0)
{
pCurr = (RingNodePtr)malloc(sizeof(RingNode));
i++;
pCurr->pos = i;
pPrev->next = pCurr;
pPrev = pCurr;
}
pCurr->next = pHead;
}
void KickFromRing(RingNodePtr pHead, int m)
{
RingNodePtr pCurr, pPrev;
int i = 1; // 计数
pCurr = pPrev = pHead;
while(pCurr != NULL)
{
if (i == m)
{
pPrev->next = pCurr->next;
free(pCurr);
pCurr = pPrev->next;
i = 1;
}
pPrev = pCurr;
pCurr = pCurr->next;
if (pPrev == pCurr)
{
printf("%d\n", pCurr->pos);
free(pCurr);
break;
}
i++;
}
}
int main()
{
int n, m;
RingNodePtr pHead = NULL;
scanf("%d %d", &n,&m);
pHead = (RingNodePtr)malloc(sizeof(RingNode));
pHead->pos = 1;
pHead->next = NULL;
CreateRing(pHead, n);
KickFromRing(pHead, m);
return 0;
}
这是一个典型的需要用双链表来解决的约瑟夫环问题
#include <stdlib.h>
typedef struct _RingNode
{
int pos;
struct _RingNode *next;
}RingNode, *RingNodePtr;
void CreateRing(RingNodePtr pHead, int count)
{
RingNodePtr pCurr = NULL, pPrev = NULL;
int i = 1;
pPrev = pHead;
while(--count > 0)
{
pCurr = (RingNodePtr)malloc(sizeof(RingNode));
i++;
pCurr->pos = i;
pPrev->next = pCurr;
pPrev = pCurr;
}
pCurr->next = pHead;
}
void KickFromRing(RingNodePtr pHead, int m)
{
RingNodePtr pCurr, pPrev;
int i = 1; // 计数
pCurr = pPrev = pHead;
while(pCurr != NULL)
{
if (i == m)
{
pPrev->next = pCurr->next;
free(pCurr);
pCurr = pPrev->next;
i = 1;
}
pPrev = pCurr;
pCurr = pCurr->next;
if (pPrev == pCurr)
{
printf("%d\n", pCurr->pos);
free(pCurr);
break;
}
i++;
}
}
int main()
{
int n, m;
RingNodePtr pHead = NULL;
scanf("%d %d", &n,&m);
pHead = (RingNodePtr)malloc(sizeof(RingNode));
pHead->pos = 1;
pHead->next = NULL;
CreateRing(pHead, n);
KickFromRing(pHead, m);
return 0;
}
这是一个典型的需要用双链表来解决的约瑟夫环问题
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询