# 约瑟夫环的循环链表实现

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

#define NUMBER 13  //可以通过输入确定人的个数
#define NEXT 8    //确定报数的间隔数
#define LENGTH sizeof(MEN)
#define NULL 0

struct men
{
int number;
struct men *pMen;
};

typedef struct men MEN;

/********************************************/
/* 约瑟夫环的循环链表实现                                       */
/********************************************/
void main()
{
MEN *pOne = NULL, *pTwo = NULL, *pHead =NULL;
int client;

/*
* 创建环形链表
*/
pHead = pOne = pTwo = (MEN *)malloc(LENGTH);
for (client = 2; client <= NUMBER; client++)
{
pOne = (MEN *)malloc(LENGTH);
pTwo->pMen = pOne;
pOne->number = client;
pTwo = pOne;
}
/*
* 进行操作
*/
pOne = pTwo->pMen;
while(pOne->pMen != pTwo)
{
for(client = 0; client < NEXT - 2;client++)
{
pTwo = pOne;
pOne = pOne->pMen;
}
//  else
pTwo->pMen = pOne->pMen;
pOne = NULL;
free(pOne);
pOne = pTwo->pMen;
pOne = pOne->pMen;
pTwo = pTwo->pMen;//保持初始状态
}
printf("%d/n", pOne->number);

}

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

#define LENGTH sizeof(MEN)
#define NULL 0

struct men
{
int   number;
int   code;
struct men *pMen;
};

typedef struct men MEN;

//////////////////////////////////////////////////////////////////////////
// 约瑟夫环的循环链表实现
//////////////////////////////////////////////////////////////////////////

void main()
{
MEN  *pOne  = NULL,
*pTwo  = NULL,
int  client;
int  NUMBER = 13; //设置默认的人数
int  NEXT = 3;     //选出的人数间隔的初始间隔数
//
// 输入人数
//
printf("请输入游戏的人数:");
scanf("%d", &NUMBER);
//
// 创建环形链表
//
pHead = pOne = pTwo = (MEN *)malloc(LENGTH);
{
printf("头结点空间分配出错!");
return;
}
//
// 初始这个链表，对头结点进行赋值
//
printf("请输入第1位的密码:");
for (client = 2; client <= NUMBER; client++)
{
pOne = (MEN *)malloc(LENGTH);

if(pOne == NULL)
{
printf("空间分配出错!");
return;
}

pTwo->pMen = pOne;
pOne->number = client;
printf("请输入第%d位的密码:", client);
scanf("%d", &pOne->code);
pTwo = pOne;
}

printf("/n被选出的次序:/n");
//
// 进行操作
//
pOne = pTwo->pMen;
while(pOne->pMen != pTwo)
{
for(client = 0; client < NEXT - 2;client++)
{
pTwo = pOne;
pOne = pOne->pMen;
}
//  else
pTwo->pMen = pOne->pMen;
//
// 释放不用的结点
//
printf(" %d ", pOne->number);
NEXT = pOne->code;
pOne = NULL;
free(pOne);

pOne = pTwo->pMen;
pOne = pOne->pMen;
pTwo = pTwo->pMen;//保持初始状态
}
printf("%d", pTwo->number);
printf("/n最后留下的是:%d/n", pOne->number);
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：约瑟夫环的循环链表实现 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)