Comprendre les "Linked lists"
Je suis rendu à apprendre comment fonctionnent les "linked lists" (je sais pas comment le dire en français) . . .
J'ai un petit bout de code, mais je n'arrive pas à comprendre à quoi sert le
Code:
struct account *previousa;
Il est utilisé dans le code, mais je ne voit pas son utilité . . .
Voici le code:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
void deleteAccount(void){
int record;
struct account *previousa;
if(firsta==NULL)
{
puts("There are no records to delete!");
return;
}
listAll(); /* show all records first */
printf("Enter account number to delete: ");
scanf("%d",&record);
currenta = firsta;
while(currenta != NULL)
{
if(currenta->number == record)
{
if(currenta == firsta) /* special condition */
firsta=currenta->next;
else
previousa->next = currenta->next;
free(currenta);
printf("Acount %d deleted!\n",record);
return;
}
else
{
previousa = currenta;
currenta = currenta->next;
}
}
printf("Account %d was not found!\n",record);
puts("Nothing deleted.");
} |
Merci beaucoup!
Alex
Edit: Voici le code qui sert à ajouter un compte (ça pourrait peut-être aider à comprendre) . . .
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
void addNewAccount(void)
{
newa = (struct account *)malloc(sizeof(struct account));
/*
* Check to see if this is the first record
* If so, then initialize all the pointers to this,
* first structure in the database
*/
if(firsta==NULL)
firsta = currenta = newa;
/*
* Otherwise, you must find the end of the structure list
* (Easily spotted by the NULL pointer) and add on the
* new structure you just allocated memory for
*/
else
{
currenta = firsta; /* make the first record the current one */
/* and loop through all records: */
while(currenta->next != NULL)
currenta = currenta->next;
/* the last record is found */
currenta->next = newa; /* save the address of new */
currenta = newa; /* make current record the new one */
}
/* Now, you just fill in the new structure */
anum++;
printf("%27s: %5i\n","Account number",anum);
currenta->number = anum;
printf("%27s: ","Enter customer's last name");
gets(currenta->lastname);
printf("%27s: ","Enter customer's first name");
gets(currenta->firstname);
printf("%27s: $","Enter account balance");
scanf("%f",¤ta->balance);
/*
* Finally, cap the new record with a NULL pointer
* so that you know it's the last record:
*/
currenta->next = NULL;
} |