第 7 课:malloc/free 与 linked list 起步
非 UNSW 官方材料。本文基于官方 Lecture 10/11 的 dynamic memory、malloc/free、multi-file projects 和 linked list 起步内容做中文转述;模板为本站原创。[S016][S017]
今天只做:创建一个 node,再用
curr走到NULL。 下一步:主控台 · 上一课 · 下一课:linked list 删除节点 别乱跳:遍历时不要改head,只移动curr。
本课目标
今天只练一件事:一个 node 里面有数据和 next,很多 node 串起来就是 linked list。[S017]
| 焚诀 | 意思 |
|---|---|
malloc | 申请一块空间 |
free | 用完还回去 |
head | 链表第一个节点 |
curr | 正在看的节点 |
创建一个节点
Lecture 11 把 malloc/free 和 linked list 放在一起讲;创建节点时先申请、再检查、再填字段。[S017]
struct node {
int data;
struct node *next;
};
struct node *create_node(int value) {
struct node *new_node = malloc(sizeof(struct node));
if (new_node == NULL) {
return NULL;
}
new_node->data = value;
new_node->next = NULL;
return new_node;
}
遍历模板
链表遍历对应 Lecture 11 的 traversal 主题;保命写法是 curr != NULL,每轮最后走到 curr->next。[S017]
void print_list(struct node *head) {
struct node *curr = head;
while (curr != NULL) {
printf("%d\n", curr->data);
curr = curr->next;
}
}
5 分钟练习
- 画
head -> [3] -> [5] -> NULL。 - 写
print_list。 - 写一句话解释
new_node->next = NULL。
本课过关标准
- 我知道
malloc后要检查NULL。 - 我知道 linked list 的终点是
NULL。 - 我能用
curr遍历,不乱改head。 - 我知道用完动态内存要
free。
引用
- [S016] Lecture 10 PDF: https://cgi.cse.unsw.edu.au/~cs1511/26T1/slides/week_5/COMP1511_26T1_Lecture10.pdf
- [S017] Lecture 11 PDF: https://cgi.cse.unsw.edu.au/~cs1511/26T1/slides/week_7/COMP1511_26T1_Lecture11.pdf