在双向链表中插入/删除的时间复杂度是 O(n) 吗?

发布于 2024-09-26 19:35:55 字数 137 浏览 0 评论 0原文

要在 DLL(双向链表)中插入/删除具有特定值的节点,需要遍历整个链表来查找位置,因此这些操作应该是 O(n)。

如果是这样的话,那么STL列表(很可能使用DLL实现)为何能够在恒定时间内提供这些操作呢?

谢谢大家给我讲清楚了。

To insert/delete a node with a particular value in DLL (doubly linked list) entire list need to be traversed to find the location hence these operations should be O(n).

If that's the case then how come STL list (most likely implemented using DLL) is able to provide these operations in constant time?

Thanks everyone for making it clear to me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

高跟鞋的旋律 2024-10-03 19:35:55

在已知位置插入和删除的时间复杂度为 O(1)。然而,找到该位置的时间复杂度为 O(n),除非它是列表的头或尾。

当我们谈论插入和删除的复杂性时,我们通常假设我们已经知道这将发生在哪里。

Insertion and deletion at a known position is O(1). However, finding that position is O(n), unless it is the head or tail of the list.

When we talk about insertion and deletion complexity, we generally assume we already know where that's going to occur.

风尘浪孓 2024-10-03 19:35:55

它不是。 STL 方法将迭代器带到要发生插入的位置,因此严格来说,它们是 O(1),因为您给了它们位置。然而,您仍然需要自己在 O(n) 中找到位置。

It's not. The STL methods take an iterator to the position where insertion is to happen, so strictly speaking, they ARE O(1), because you're giving them the position. You still have to find the position yourself in O(n) however.

捎一片雪花 2024-10-03 19:35:55

删除任意值(而不是节点)确实是 O(n),因为它需要找到该值。删除一个节点(即当您开始了解该节点时)的复杂度为 O(1)。

基于值插入 - 例如插入排序列表 - 将为 O(n)。如果在现有已知节点之后或之前插入,则时间复杂度为 O(1)。

插入到列表的头部或尾部总是 O(1) - 因为这些只是上述情况的特殊情况。

Deleting an arbitrary value (rather than a node) will indeed be O(n) as it will need to find the value. Deleting a node (i.e. when you start off knowing the node) is O(1).

Inserting based on the value - e.g. inserting in a sorted list - will be O(n). If you're inserting after or before an existing known node is O(1).

Inserting to the head or tail of the list will always be O(1) - because those are just special cases of the above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文