# 如何编写修改链表头指针的C函数？

1)不会修改头指针的函数：

``````void addXtoList( struct Node *node, int x)
{
while (node != NULL)
{
node->data = node->data + x;
node = node->next;
}
}``````

2)修改头指针的函数：例如, 在开头插入一个节点(在此功能中始终修改头指针), 在结尾插入一个节点(仅在插入第一个节点时修改头指针), 删除给定节点(修改头指针)当删除的节点是第一个节点时)。在这些功能中, 可能有不同的方法来更新头指针。让我们使用以下简单问题讨论这些方式：

“给出一个链表, 编写一个函数deleteFirst()来删除给定链表的第一个节点。例如, 如果列表为1-> 2-> 3-> 4, 则应将其修改为2-> 3-> 4”

2.1)使头指针全局化：

``````//global head pointer
struct Node *head = NULL;

//function to delete first node: uses approach 2.1
//See http://ideone.com/ClfQB for complete program and output
void deleteFirst()
{
if (head != NULL)
{
//store the old value of head pointer
struct Node *temp = head;

//Change head pointer to point to next node

//delete memory allocated for the previous head node
free (temp);
}
}``````

b)如果有多个链接列表, 则需要多个具有不同名称的全局头指针。

2.2)返回头指针：

``````//function to delete first node: uses approach 2.2
//See http://ideone.com/P5oLe for complete program and output
struct Node *deleteFirst( struct Node *head)
{
if (head != NULL)
{
//store the old value of head pointer
struct Node *temp = head;

//Change head pointer to point to next node

//delete memory allocated for the previous head node
free (temp);
}

}``````

``````head = deleteFirst(head);  //proper use of deleteFirst()
deleteFirst(head);  //improper use of deleteFirst(), allowed by compiler``````

2.3)使用双指针：

``````//function to delete first node: uses approach 2.3
//See http://ideone.com/9GwTb for complete program and output
void deleteFirst( struct Node **head_ref)
{
if (*head_ref != NULL)
{
//store the old value of pointer to head pointer
struct Node *temp = *head_ref;

//Change head pointer to point to next node

//delete memory allocated for the previous head node
free (temp);
}
}``````

• 回顶