שפת C/ניהול זיכרון דינאמי: הבדלים בין גרסאות בדף
תוכן שנמחק תוכן שנוסף
שורה 588:
===כימוס
נחשוב ראשית מה הפעולות שבהן היינו רוצים שרשימה תתמוך. להלן הצעה אפשרית לרשימה כזאת:
*פעולה שיוצרת רשימה
*פעולה שהורסת רשימה בתום השימוש (כולל שחרור משאבים שטרם שוחררו)
*שאילתה לגבי מספר האיברים
*דחיפת איבר לראש הרשימה
*שליפת איבר מראש הרשימה
*שאילתה לגבי האיבר בראש הרשימה
כדי לתמוך בפעולות הנ"ל, אפשר לממש רשימה כמבנה ששדותיו הם מצביע לראש הרשימה ומונה למספר האיברים ברשימה:
<source lang = "c">
struct list_
שורה 599 ⟵ 609:
typedef struct list_ list;
</source>
להלן ההצהרות לפעולות שבהן רצינו שרשימה תתמוך:
<source lang = "c">
/* Constructs a list (prepares it for use). */
void list_ctor(list *list);
/* Destructs a list (after use). */
void list_dtor(list *list);
/* Returns the number of elements in the list. */
unsigned long list_size(const list *list);
/* Pushes new data to the head of the list.
* Returns 0 if the operation succeeded, -1 otherwise. */
int list_push(list *list, int data);
/* Pops (removes) the element at the head of the list.
* Returns the element.
* Don't call if the size of the list is 0. */
int list_pop(list *list);
/* Returns the element at the head of the list.
* Don't call if the size of the list is 0. */
int list_head(const list *list);
</source>
כעת נוכל לממש כל אחת מפעולות אלו.
<source lang = "c">
void list_ctor(list *list)
|