带头结点的链式表操作集
时间: 2025-07-06 13:58:51 浏览: 6
### 带头结点的链表常用操作方法及实现
#### 创建带头结点的单链表
创建一个带头结点的单链表通常涉及初始化一个空链表,即仅有一个头结点而无其他数据节点。这可以通过分配一个新的结点作为头结点并将其`next`指针设置为`NULL`来完成。
```c
struct Node {
int data;
struct Node *next;
};
// 初始化带头结点的链表
void initList(struct Node **L) {
(*L) = (struct Node *)malloc(sizeof(struct Node));
if (!(*L)) exit(-1); // 内存不足处理
(*L)->next = NULL;
}
```
#### 插入元素到带头结点的单链表中
向带头结点的单链表插入新元素可以在任意位置执行,但最常见的是在头部或尾部插入。这里展示如何在链表头部插入新元素[^2]:
```c
void insertAtHead(struct Node **L, int value) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = (*L)->next; // 新节点指向原来的第一个真实节点
(*L)->next = newNode; // 头结点现在指向新的节点
}
```
#### 删除指定值的第一个匹配项
删除带有特定值的第一个出现的节点需要遍历整个列表直到找到该值为止,并调整前驱节点的`next`指针以跳过目标节点[^3]。
```c
int deleteFirstOccurrence(struct Node **L, int targetValue) {
struct Node *current = (*L);
struct Node *previous = NULL;
while ((current != NULL) && (current->data != targetValue)) {
previous = current;
current = current->next;
}
if (current == NULL) return 0; // 如果未找到则返回失败标志
if (previous == NULL) { // 当要删除的是首元节点的情况
(*L) = current->next;
} else {
previous->next = current->next;
}
free(current);
return 1; // 成功删除标记
}
```
#### 遍历打印所有元素
最后,提供一种简单的方式用于遍历并显示链表中的每一个元素[^1]。
```c
void traverseAndPrint(struct Node *L) {
L = L->next; // 跳过头结点
while(L != NULL){
printf("%d ", L->data);
L = L->next;
}
printf("\n");
}
```
阅读全文
相关推荐

















