当列表为空时,链表通常使用 NULL 头来实现。在这种情况下,当头部是局部变量时,或者当它是全局变量并且您希望使用相同的函数拥有多个列表时,您必须返回列表的头部。添加节点时,头部可能已经改变,即使在尾部添加,如果列表为空,则会有一个新的头部。
但另一种方法是始终在头部有一个节点,只是在这里表示头部,并在此头部之后添加/读取/删除节点以处理列表中的数据。在这种情况下,返回头部是没有用的,因为头部永远不会改变。
您可以在节点 n:n->next == NULL 时检测列表的尾部,当列表为空时使用等于 NULL 的头部,如下代码所示:
// add at the tail of the list:
struct node * add_to_list_tail(struct node * head,int v) {
struct node *t;
t=(struct node *) malloc(sizeof(struct node));
t->value = v;
t->next = NULL; // next is set to NULL because it is the new tail
if(head == NULL) {
// in the case the list is empty
head = t; // t become the new head, because the list was empty
} else {
// in the case the list isn't empty
struct node * n = head;
// the following loop will stop when n->next == NULL, and n will point to the tail
while(n->next != NULL) {
n = n->next;
}
n->next = t;
}
return head;
}
// add at the head of the list:
struct node * add_to_list(struct node * head,int v) {
struct node *t;
t=(struct node *) malloc(sizeof(struct node));
t->value = v;
t->next = head; // make t become the new head
return t; // return t because it is the new head
}
int main() {
struct node * head = NULL;
head = add_to_list(head,1);
head = add_to_list(head,2);
head = add_to_list_tail(head,3);
}
如果你不想返回头部,你也可以传递一个指向头部指针的指针,作为操作列表的函数的参数。一个简短的示例代码:
void add_to_list(struct node ** head,int v) {
struct node *t;
t=(struct node *) malloc(sizeof(struct node));
t->value = v;
// make t become the new head:
t->next = *head;
*head = t;
}
int main() {
struct node * head = NULL;
// we pass &head, the adress of variable head, as parameter:
add_to_list(&head,1);
add_to_list(&head,2);
struct node * n = head;
while(n != NULL) {
printf("\nvalue: %d",n->value);
n = n->next;
}
}