我正在尝试为圣诞老人制作一个程序!我的知识有限;我迷失在指针和循环等中,我已经思考了几个小时。
我有一个指向单向链表的指针数组。每个数组索引表示年龄组 0:0-3、1:4-7、2:8-11、3:11-15 的 child 列表。
每个 child 都是一个结构,现在每年我都想遍历所有列表,将他们的年龄增加 1,如果他们需要更改年龄组,我必须将节点移动到包含那个年龄段。如果 child 已经超过 15 岁,那么它必须删除该节点。我的代码不完整,因为我是链表的新手,我很困惑。
我的主要问题是我在列表中移动时对列表进行了更改,因此如果我检查第一个节点并将其删除,我必须再次检查第一个节点,因为现在它是一个新节点,所以我继续检查直到 Head 没问题,这是正确的方法吗?我不确定我的代码是否有效,我还不能测试它。
来 self 的 Santa_Claus.h 的部分:
/*Structure defining a node of the children list*/
struct child {
int cid; /*The identifier of the child.*/
int age; /*The age of the child.*/
int did; /*The identifier of the child.*/
int present_choices[M]; /*The array in which the preferences of the child for presents are stored*/
struct child *next; /* Singly-linked, sorted by id */
};
来自Santa_Claus.c的部分
#define N 4 /*Number of children's age categories*/
struct child *Age_categories[N];
int new_season(void) {
int i;
struct child *childP = NULL;
struct child *prev = NULL;
struct child *childptr = NULL;
int MaxAges[N] = {3,7,11.15};
//Increment Age Loop
for(i = 0; i < N; i++){
childP = Age_categories[i];
while(childP != NULL){
childP->age = childP->age + 1;
childP = childP->next;
}
}
//Remove or Move Loop
for(i = 0; i < N; i++){
childP = Age_categories[i];
//while the first is still > than the max age of this category
while(childP->age > MaxAges[i]){
if(i != (N-1)){
childP->next = Age_categories[i+1];
Age_categories[i+1] = childP;
}else{
Age_categories[i] = childP->next;
}
childP = childP->next;
}
prev = Age_categories[i];
childP = prev->next;
while(childP != Null){
if(childP->age > MaxAges[i]){
if(i != (N-1)){
prev->next = childP->next;
childP->next = Age_categories[i+1];
Age_categories[i+1] = childP;
}else{
Age_categories[i] = childP->next;
}
}
prev = childP;
childP = childP->next;
}
}
return 1;
}
最佳答案
My main issue is that I make changes to the lists as I move through them, so if I check for the first node and I remove it, I have to check the first node again because now its a new one, so I keep checking until the Head is okay, is this the right approach?
就地编辑会在边缘情况下咬你。您将遇到头节点和尾节点的问题。如果你移除头部,那么任何跟踪你头部的东西现在都指向零空间。
简而言之,你只需要小心。有很多方法可以搞砸它。对于新手,我建议您远离 C 中的指针。功能强大,但很麻烦。除非你真的需要这个东西来扩展,否则坚持使用固定阵列。
您不需要重新检查头部,只要有一个特殊情况即可检查头部,并进行头部安全编辑。同时检查集合是否为空,并检查尾部通常是个好主意。您可以尝试想出一些聪明的方法来避免这种事情,并使用流畅的代码来处理这一切......但是聪明的代码通常也会同样地咬你的屁股。
关于C - 根据值移动或删除多个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340994/