之所以将这段代码再敲一次,因为这段代码有几点值得学习。
1.对于链表,可以很方便的在表头插入数据,但是如果保留一个尾节点,则可以很方便的尾部插入节点。
2.不用专门定义一个指针来保留欲删除节点的父节点,只需要在数数的时候少数一个即可。如代码中:if( count == stride - 1)
代码示例:
#include <stdio.h>
struct Monkey
{
int ID;
Monkey *next;
};
int main(int argc, char* argv[])
{
Monkey *link, *monkey, *lastMonkey;
int totalMonkeys, stride, count;
printf("Please input the numbers of Monkeys:\n");
scanf("%d", &totalMonkeys);
printf("Please input a number for striding:\n");
scanf("%d", &stride);
link = NULL;
for( int i = 0; i < totalMonkeys; i++)
{
monkey = new Monkey;
monkey ->ID = i + 1;
if( link == NULL)
{
link = lastMonkey = monkey;
}
else
{
lastMonkey->next = monkey;
lastMonkey = monkey;
}
}
lastMonkey->next = link;
count = 1;
printf("猴子出队的顺序:");
while( link != NULL)
{
if( link->next == link )
{
printf("%4d\n", link->ID);
delete link;
break;
}
if( count == stride - 1)
{
monkey = link->next;
link->next = monkey->next;
printf("%4d", monkey->ID);
delete monkey;
monkey = NULL;
count = 0;
}
link = link->next;
count++;
}
return 0;
}
本文介绍了一个使用链表实现猴子淘汰游戏的C语言程序。通过在链表头部和尾部进行节点插入,简化了节点管理和删除过程。代码展示了如何在不保留额外指针的情况下高效地进行节点删除。
559

被折叠的 条评论
为什么被折叠?



