mathmari
Gold Member
MHB
- 4,984
- 7
I like Serena said:The first is correct! (Smile)
But the second is not. (Worried)
Sentinal is a data member of StarS[k], and not of last->next.
You should set StarS[k].Sentinal to last->next, which is by now the same as plansystem.Alternatively, you could do at the end: [m]StarS[k].Sentinal = plansystem[/m].
That works because [m]plansystem[/m] is always added to the end, wherever that is. So afterwards it is the last node in the list, which is where [m]Sentinal[/m] should point. (Nerd)
Do you mean that we could write it as followed??
Code:
int Beginning(int solid, int ss){
int i, k=-1;
/* Add a planetary system to the list of the planetary system of the star system */
plansys_t *plansystem = calloc(1, sizeof(plansys_t));
plansystem->solid=solid;
plansystem->asteroids=NULL;
plansystem->next=NULL;
for(i=0; i<Sfreep; i++){
if(StarS[i].ss==ss){
k=i;
if (StarS[k].plasy == NULL) {
/* List is empty: replace with new plansystem */
StarS[k].plasy = plansystem;
} else {
/* Find last node */
plansys_t *last = StarS[k].plasy;
while (last->next != NULL) {
last = last->next;
}
/* Append new plansystem to the last node */
last->next = plansystem;
}
StarS[k].Sentinal = plansystem;
}
}
return k;
}
(Wondering)
I like Serena said:The way the code is indented, it is hard to follow the flow of the program, and understand if and where something is wrong and should be changed. (Sweating)
Better is:
Code:int Beginning(int solid, int ss){ int i, k = -1; /* Add a planetary system to the list of the planetary system of the star system */ plansys_t *plansystem = calloc(1, sizeof(plansys_t)); plansystem->solid = solid; plansystem->asteroids = NULL; plansystem->next = NULL; for(i=0; i<Sfreep; i++){ if(StarS[i].ss == ss){ k=i; if (StarS[k].plasy == NULL) { /* List is empty: replace with new plansystem */ StarS[k].plasy = plansystem; StarS[k].Sentinel = StarS[k].plasy; } else { /* Find last node */ plansys_t *last = StarS[k].plasy; while (last->next != NULL) { last = last->next; } /* Append new plansystem to the last node */ last->next = plansystem; last->next->Sentinel = last; } } } return k; }
Like this it becomes clear where the for-loop starts and ends, where the first if-statement is, and where the nested if-else statement is (and that there is one). (Whew)
Ok! (Blush)