Skip to content

Commit

Permalink
Merge pull request #2480 from Chaobk/main
Browse files Browse the repository at this point in the history
LinkedList指定位置插入/删除,遍历平均元素应该是n/4个元素
  • Loading branch information
Snailclimb authored Sep 9, 2024
2 parents 94bf6cb + 3940439 commit e06114f
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 2 deletions.
2 changes: 1 addition & 1 deletion docs/java/collection/java-collection-questions-01.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ System.out.println(listOfStrings);

- 头部插入/删除:只需要修改头结点的指针即可完成插入/删除操作,因此时间复杂度为 O(1)。
- 尾部插入/删除:只需要修改尾结点的指针即可完成插入/删除操作,因此时间复杂度为 O(1)。
- 指定位置插入/删除:需要先移动到指定位置,再修改指定节点的指针完成插入/删除,因此需要遍历平均 n/2 个元素,时间复杂度为 O(n)。
- 指定位置插入/删除:需要先移动到指定位置,再修改指定节点的指针完成插入/删除,不过由于有头尾指针,可以从较近的指针出发,因此需要遍历平均 n/4 个元素,时间复杂度为 O(n)。

这里简单列举一个例子:假如我们要删除节点 9 的话,需要先遍历链表找到该节点。然后,再执行相应节点指针指向的更改,具体的源码可以参考:[LinkedList 源码分析](./linkedlist-source-code.md)

Expand Down
2 changes: 1 addition & 1 deletion docs/java/collection/linkedlist-source-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ tag:

- 头部插入/删除:只需要修改头结点的指针即可完成插入/删除操作,因此时间复杂度为 O(1)。
- 尾部插入/删除:只需要修改尾结点的指针即可完成插入/删除操作,因此时间复杂度为 O(1)。
- 指定位置插入/删除:需要先移动到指定位置,再修改指定节点的指针完成插入/删除,因此需要移动平均 n/2 个元素,时间复杂度为 O(n)。
- 指定位置插入/删除:需要先移动到指定位置,再修改指定节点的指针完成插入/删除,不过由于有头尾指针,可以从较近的指针出发,因此需要遍历平均 n/4 个元素,时间复杂度为 O(n)。

### LinkedList 为什么不能实现 RandomAccess 接口?

Expand Down

0 comments on commit e06114f

Please sign in to comment.