--- config: look: handDrawn themeVariables: fontSize: 20px --- mindmap Python风格列表 列表结点定义 列表长度 列表打印 追加节点 索引节点 列表切片
《计算机程序设计》
计算机学院计算机研究所编译系统研究室
~/course
~/course/main.cpp
main.cpp
,随堂编程练习的代码请直接在此文件中编辑任务
本次综合练习中,基于C++链表实现Python风格列表,支持以下操作
操作 | 说明 |
---|---|
int len(Node *list) |
获取列表长度 |
void print(Node *list) |
打印列表 |
Node *appendInt(Node *&list, int x) |
在列表末尾添加整数结点 |
Node *appendStr(Node *&list, const char *s) |
在列表末尾添加字符串结点 |
Node *get(Node *list, int index) |
索引操作,支持负向索引 |
Node *slice(Node *list, int start, int end, int step) |
切片操作 |
学习目标
综合运用结构体、联合体、枚举类型、链表、指针、函数等知识构建实用数据结构
len
函数,获取列表长度考考你
列表长度函数可以通过一次遍历实现,可否应用相同的程序结构实现列表打印函数?
print
函数,打印列表appendInt
与appendStr
函数,向列表末尾追加结点get
函数,根据索引值返回结点指针
nullptr
考考你
应该如何支持负向索引?提示:考虑正向索引与负向索引的有效取值范围
\[i \leftarrow j + n\]
slice
函数,根据切片参数返回子链表
考考你
切片参数start
、end
、step
分别表示起始索引、结束索引与步长,都有哪些情况应判定为无效切片?
step == 0
step > 0
但start >= end
step < 0
但start <= end
start
与end
其中任意一个越界slice
函数,根据切片参数返回子链表
考考你
如何从一个有效索引创建新的列表?
列表切片
Node *slice(Node *list, int start, int end, int step) {
// 索引正则化
int n = len(list);
if (start < 0) start += n;
if (end < 0) end += n;
// 无效切片判定
if (step == 0 || (step > 0 && start >= end) || (step < 0 && start <= end) ||
(start < 0 || start >= n) || (end < 0 || end >= n))
return nullptr;
// 创建新链表
Node *slice = nullptr;
if (step > 0) {
for (int i = start; i < end; i += step) {
Node *p = get(list, i);
Node *q = new Node; *q = *p; q->next = nullptr;
append(slice, q);
}
} else {
for (int i = start; i > end; i += step) {
Node *p = get(list, i);
Node *q = new Node; *q = *p; q->next = nullptr;
append(slice, q);
}
}
return slice;
}
--- config: look: handDrawn themeVariables: fontSize: 20px --- mindmap Python风格列表 列表结点定义 列表长度 列表打印 追加节点 索引节点 列表切片
学习目标
综合运用结构体、联合体、枚举类型、链表、指针、函数等知识构建实用数据结构
计算机程序设计