链表
查找结点
在查找元素时,链表不像数组那样可以通过下标快速进行定位,只能从头结点开始向后一个一个结点逐一查找。
链表中的数据只能按顺序进行访问,最坏的时间复杂度是 。
C
T singly_linked_list_get(singly_linked_list_t *list, int index) {
if (list == NULL) {
exit(1);
}
if (index < 0 || index >= list->size) {
fprintf(stderr, "Error: index out of bound.\n");
exit(1);
}
if (index == list->size - 1) {
return list->tail->data;
}
node_t *node = list->head;
for (int i = 0; i < index; i++) {
node = node->next;
}
return node->data;
}对于单向链表,只能从 head 沿 next 向后查找。双向链表既可以从 head 向后查找,也可以从 tail 沿 prev 向前查找。循环链表查找时不能以 NULL 作为停止条件;指针再次回到起点时,说明已经检查了全部结点。
知识测验
题目
一个双向链表有 10 个结点,下标为 0–9,已知 head 和 tail。查找下标 8 的结点,最少需要沿多少条链接移动?