pNode cur = NULL; //当前节点
pNode pre = NULL; //当前结点的前一个节点
pNode head = NULL; //头节点
/****以下为单循环链表创建一个n个数的约瑟夫环*****/
pNode CreateNode( DataType n)
{
int i = 0;
for (i = 1; i <= n;i++)
{
pNode tmp = (pNode)malloc(sizeof(Node));
if (NULL == tmp)
{
printf("内存不够了 !\n"); //提升健壮性,针对内存不足的情况所做的应对
exit(EXIT_FAILURE);
}
else
{
cur = tmp;
cur->data = i;
cur->next = NULL;
}
if (head == NULL)
{
head = cur;
}
else
{
pre->next = cur;
}
pre = cur;
}
cur ->next = head; //链表的尾节点指向头节点形成环,体现循环链表的特点-循环
return head;
}
void JosephCircle(DataType num, DataType count)
{
int i = 0;
int j = 0;
cur =CreateNode(num);
while (cur->next != cur) //判断链表中是否达到游戏停止的条件只剩下一只猴子
{
for (i = 1; i <num ;i++)
{
for (j = 1;j < count ; j++)
{
pre = cur;
cur = cur->next; //从头继续开始
}
printf("第%d个出局的猴子是第(%d )位\n", i, cur->data);
pre->next = cur->next;
free(cur);
cur = pre->next;
}
}
printf("最终留下来的猴子是第( %d )位\n", cur->data);
}
int main()
{
int num; //约瑟夫环总人数
int count; //出局的猴子所代表的数
printf("请输入参加这场约瑟夫环问题的猴子数: ");
scanf("%d", &num);
printf("请输入是第几个报数的猴子为出局数: ");
scanf("%d", &count);
JosephCircle( num, count);
return 0;
}
“pNode tmp = (pNode)malloc(sizeof(Node));”是怎么操作的,含义分析
“if (NULL == tmp)”中 tmp 代表什么含义
“pNode CreateNode( DataType n)”
这个函数最好能详细解释一下。
谢谢!!