C语言实现单向链表加注释
时间: 2023-07-11 18:48:42 浏览: 67
以下是C语言实现单向链表并加上注释的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单向链表结构体
struct Node {
int data; // 数据域
struct Node* next; // 指针域
};
int main() {
// 初始化链表头节点
struct Node* head = NULL;
// 创建链表节点并赋值
struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));
node1->data = 1;
node1->next = NULL;
// 将节点1插入链表头
head = node1;
// 创建链表节点并赋值
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
node2->data = 2;
node2->next = NULL;
// 将节点2插入链表尾
node1->next = node2;
// 遍历链表并输出每个节点的值
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
// 释放链表节点的内存
current = head;
while (current != NULL) {
struct Node* temp = current;
current = current->next;
free(temp);
}
return 0;
}
```
注释中解释了每个关键步骤的功能,可以帮助理解代码的实现过程。需要注意的是,链表的节点插入和遍历是常见操作,而释放内存也是必要的,避免内存泄漏。