以下是使用C语言创建链表并循环打印的代码:
#include
#include
/* 定义链表节点结构体 */
struct Node {
int data; // 节点存储的数据
struct Node* next; // 指向下一个节点的指针
};
/* 创建链表并返回头节点指针 */
struct Node* createLinkedList() {
// 创建三个节点指针并分配内存
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
// 检查内存分配是否成功
if (!head || !second || !third) {
printf("内存分配失败!\n");
exit(1); // 分配失败则退出程序
}
// 初始化头节点
head->data = 1;
head->next = second; // 头节点指向第二个节点
// 初始化第二个节点
second->data = 2;
second->next = third; // 第二个节点指向第三个节点
// 初始化第三个节点
third->data = 3;
third->next = NULL; // 第三个节点作为尾节点
return head; // 返回链表头节点
}
/* 遍历并打印链表内容 */
void printLinkedList(struct Node* head) {
struct Node* current = head; // 从头节点开始遍历
printf("链表内容: ");
while (current != NULL) { // 循环直到节点为空
printf("%d -> ", current->data); // 打印当前节点数据
current = current->next; // 移动到下一个节点
}
printf("NULL\n"); // 表示链表结束
}
int main() {
// 创建链表
struct Node* head = createLinkedList();
// 打印链表
printLinkedList(head);
// 释放链表内存(防止内存泄漏)
struct Node* current = head;
while (current != NULL) {
struct Node* temp = current; // 临时保存当前节点
current = current->next; // 移动到下一个节点
free(temp); // 释放当前节点内存
}
return 0;
}
代码详细说明
- 结构体定义:
- struct Node 定义了链表的节点结构,包含:
- data:存储整型数据。
- next:指向下一个节点的指针(struct Node* 类型)。
- 创建链表函数 (createLinkedList):
- 动态内存分配:使用 malloc 为三个节点分配内存。
- 错误检查:若内存分配失败,打印错误信息并退出程序。
- 节点初始化:
1)头节点存储数据 1,指向第二个节点。
2)第二个节点存储数据 2,指向第三个节点。
3)第三个节点存储数据 3,next 设置为 NULL 表示链表结束。
- 打印链表函数 (printLinkedList):
- 从头节点开始遍历链表。
- 使用 while 循环逐个访问节点,直到遇到 NULL。
- 打印每个节点的数据,格式为 数据 ->,最后以 NULL 结尾。
- 主函数 (main):
- 调用 createLinkedList 创建链表。
- 调用 printLinkedList 打印链表内容。
- 内存释放:遍历链表并逐个释放节点内存,避免内存泄漏。
执行结果
链表内容: 1 -> 2 -> 3 -> NULL
关键点说明
- 动态内存管理:使用 malloc 分配内存后,必须用 free 释放,防止内存泄漏。
- 链表结构:每个节点通过 next 指针连接,最后一个节点的 next 为 NULL。
- 遍历操作:通过循环依次访问每个节点,直到 next 指针为 NULL。