我正在嘗試爲聖誕節做一個程序!我的知識是有限的;我迷失在指針和循環等中,我一直在想這個幾個小時。C - 根據值移動或刪除多個節點
我有一個指針數組來單鏈表。每個數組索引表示兒童的年齡組0的列表:0-3,1:4-7,2:8-11,3:11 - 15
每個孩子都是一個struct,每年我現在後想要遍歷所有列表,將其年齡增加1,如果他們需要更改年齡組,則必須將節點移至包含該年齡組的適當列表。如果孩子的年齡超過15歲,則必須刪除該節點。我的代碼是不完整的,因爲我是鏈接列表的新手,我感到困惑。
我的主要問題是當我移動它們時,我對列表進行了更改,因此如果我檢查第一個節點並刪除它,我必須再次檢查第一個節點,因爲現在它是一個新節點,所以我繼續檢查,直到頭部沒問題,這是正確的方法嗎?我不確定我的代碼是否有效,但我無法測試它。
部分從我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;
}
問題是什麼/問題嗎? –
需要「漂亮/淘氣」布爾型。 –
@AntoineMathys感謝您的時間採取LO好吧。我猜我必須回過頭來逐一對列表進行排序,我想呢?即使它效率不高。當我在列表中移動時,有太多的事情正在進行,我迷了路! –