从
linked-list标签维基摘录:
A linked list is a data structure in which the elements contain
references to the next (and optionally the previous) element. Linked
lists offer O(1) insert and removal at any position, O(1) list
concatenation, and O(1) access at the front (and optionally back)
positions as well as O(1) next element access. Random access has O(N)
complexity and is usually unimplemented.
(强调我的)
我很惊讶地读到这个 - 列表如何插入一个随机索引比复杂度低于简单的读取索引?
public void add(int index, E element) {
addBefore(element, (index==size ? header : entry(index)));
}
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
即使使用半尺寸优化,这里的一个(一个或另一个)的循环似乎是一个死亡的赠品,这个方法(因此add(int,E))在最小的最坏情况下运行O(n )时间,当然不是时间.
我失踪了什么我误解了大O表示法吗?