在C语言中,链表是一种常见的数据结构,用于动态存储和管理数据。链表由一系列节点组成,每个节点包含数据部分和指向下一个节点的指针。在没有头/尾指针的情况下,添加多个节点到链表中需要一些额外的步骤来维护链表的完整性。
以下是一个示例代码,展示了如何在没有头/尾指针的情况下向链表中添加多个节点:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 函数声明
void addNode(struct Node** head, int data);
void printList(struct Node* head);
int main() {
struct Node* head = NULL; // 初始时链表为空
// 添加多个节点
addNode(&head, 10);
addNode(&head, 20);
addNode(&head, 30);
// 打印链表
printList(head);
return 0;
}
// 添加节点到链表的函数
void addNode(struct Node** head, int data) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
// 如果链表为空,新节点成为头节点
if (*head == NULL) {
*head = newNode;
} else {
// 遍历链表找到最后一个节点
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
// 将新节点连接到最后一个节点后面
current->next = newNode;
}
}
// 打印链表的函数
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
malloc
函数动态分配内存给新节点,并初始化其数据和指针。struct Node** head
),可以在函数内部修改头指针的值。current->next == NULL
)。next
指针设置为NULL
,并将其连接到最后一个节点的next
指针上。malloc
返回NULL
,表示内存分配失败,应进行错误处理。通过上述方法,可以在没有头/尾指针的情况下有效地向链表中添加多个节点。
领取专属 10元无门槛券
手把手带您无忧上云