רשימה מקושרת

alex11m

New member
רשימה מקושרת

יש לי מבנה כזה:
struct list { int num; struct list *next; };​
וראיתי שכדי להוסיף איבר לראש הרשימה יש להשתמש בפרוצדורה הזאת:
void add (struct list** head, int num) { struct list* second = *head; *head = (struct list*)malloc(sizeof(struct list)); (*head)->num = num; (*head)->next = second; }​
אני לא מבין את הפרמטר struct list** head על מה הוא מצביע ולמה אני צריך אותו. הנה התוכנית המלאה:
#include <stdio.h> #include <conio.h> #include <stdlib.h> const int MAX = 3; struct list { int num; struct list *next; }; void add (struct list** head, int num) { struct list* second = *head; *head = (struct list*)malloc(sizeof(struct list)); (*head)->num = num; (*head)->next = second; } void build_list (struct list** head) { int i, num; for (i = 0; i < MAX; i++) { num = random(10); add(head, num); } } void display_list (struct list* head) { struct list* temp = head; printf ("\nThe members of the list are: \n\n"); while (temp != NULL) { printf (" %d ", temp->num); temp = temp->next; } temp = head; printf("\n"); while (temp != NULL) { printf ("%p ", temp); temp = temp->next; } } void del_member (struct list** head) { struct list *temp = *head; *head = (*head)->next; printf ("%p\t", temp); free(temp); } void delete_list (struct list** head) { printf("\n\nDeleting the list\n"); while (*head) del_member (head); } void main() { struct list* head = NULL; randomize(); build_list (&head); display_list (head); delete_list (&head); }​
 

DarkSwell

New member
תשובה..

head הוא המצביע לראש הרשימה. הפונקציה הזו מקבלת את כתובתו של המצביע על כן **, היא מקבלת את כתובתו על מנת שתוכל לשנות את ערכו. האיבר החדש שנוסף לרשימה נוסף בראש הרשימה לכן head צריך לקבל את כתובתו.
 
למעלה