#include <stdio.h>
#include <stdlib.h>
#define MAX_NODE_NUM 30
#define TRUE 1U
#define FALSE 0U
typedef struct NodeType
{
int id;
int password;
struct NodeType* next;
}NodeType;
NodeType;
static void CreaList(NodeType**, const int);
static void StatGame(NodeType**, int);
static void PrntList(const NodeType*);
static NodeType* GetNode(const int, const int);
static unsigned EmptyList(const NodeType*);
int main(void)
{
int n, m;
int iflag = 1;
NodeType* pHead = NULL;
{
printf("---------------------------------------\n");
printf("------欢迎进入‘约瑟夫环’运行界面----------\n");
printf("----按照指示运行程序---------------\n");
printf("---------------------------------------\n");
}
while (iflag == 1)
{
printf("请输入人数:");
scanf_s("%d", &n);
printf("初始密码m:");
scanf_s("%d", &m);
if (n > MAX_NODE_NUM)
{
printf("人数过大,请重新输入:\n");
continue;
}
CreaList(&pHead, n);
printf("\n---------输入密码-----------\n");
PrntList(pHead);
printf("\n---------出列顺序-----------\n");
StatGame(&pHead, m);
pritnf("是否继续游戏?输入1继续,输入0退出\n");
scanf_s("%d", &iflag);
}
return 0;
}
static void CreaList(NodeType** ppHead, const int n)
{
int i, iCipher;
NodeType* pNew, * pCur;
for ( i = 0; i <= n; i++)
{
printf("输入第%d个人的密码:", i);
scanf_s("%d", &iCipher);
pNew = GetNode(i, iCipher);
if (*ppHead == NULL)
{
*ppHead = pCur = pNew;
pCur->next = *ppHead;
}
else
{
pNew->next = pCur->next;
pCur->next = pNew;
pCur = pNew;
}
}
printf("约瑟夫环定义成功\n");
}
static void StatGame(NodeType** ppHead, int iCipher)
{
int iCounter, iFlag = 1;
NodeType* pPrv, * pCur, *pDel;
pPrv = pCur = *ppHead;
while (pPrv->next != *ppHead)
pPrv = pPrv->next;
while (iFlag)
{
for (iCounter = 0; iCounter < iCipher; iCounter++)
{
pPrv = pCur;
pCur = pCur->next;
}
if (pPrv == pCur)
iFlag = 0;
pDel = pCur;
pPrv->next = pCur->next;
pCur = pCur->next;
iCipher = pDel->password;
printf("第%d个人出列,他的密码是:%d\n", pDel->id, pDel->password);
free(pDel);
}
*ppHead = NULL;
}
static void PrntList(const NodeType* pHead)
{
const NodeType* pCur = pHead;
if (Emptylist(pHead))
return;
do
{
printf("第%d个人,密码:%d\n", pCur->id,pCur->password);
pCur = pCur->next;
} while (pCur != pHead);
}
static NodeType* GetNode(const int iId, const int iCipher)
{
NodeType* pNew;
pNew = (NodeType*)malloc(sizeof(NodeType));
if (!pNew)
{
printf("error,the memory is not enough!\n");
exit(-1);
}
pNew->id = iId;
pNew->password = iCipher;
pNew->next = NULL;
return pNew;
}
static unsigned EmptyList(const NodeType *pHead)
{
if (!pHead)
{
printf("这个约瑟夫环里没有人!\n");
return TRUE;
}
return FALSE;
}