[英]How to handle the root of a Singly-Linked List
假設我在鏈接列表中有一個節點,定義如下:
struct movie {
char title[50];
int year;
};
// so we can swap in other types by changing the `typedef Item`
typedef struct movie Item;
struct node {
Item item;
struct node *next;
};
通常如何處理列表的頭/根? 這是否像這樣做一樣簡單:
struct node *head;
還是LinkedList
通常作為包裝結構處理,例如:
struct LinkedList_ {
struct node* head;
size_t size;
// anything else?
} LinkedList;
我們只是使用LinkedList
並圍繞該項目添加功能? 例如: LinkedList->addNode(...)
。
這里真的沒有對錯。 這更像是一個設計決定,而不是其他任何事情。 就我個人而言,我通常不使用任何類型的包裝器,也不存儲大小,因為列表的末尾由 null 指針標記。 所以要迭代它,我通常使用這樣的東西:
for(struct node *current = first; current != NULL; current = current->next);
我還存儲了頭部和尾部。 因此,您可以輕松地將節點添加到列表中。
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.