我使用了很多列表和数组,但我还没有遇到一个场景,数组列表不能像链表一样容易使用,如果不是更容易的话。我希望有人能给我一些例子,说明什么时候链表明显更好。
当前回答
1)如上所述,与ArrayList(O(n))相比,在LinkedList中插入和删除操作具有良好的性能(O(1))。因此,如果应用程序需要频繁的添加和删除,那么LinkedList是最好的选择。
2)搜索(get方法)操作在Arraylist (O(1))中是快速的,但在LinkedList (O(n))中不是,所以如果有更少的添加和删除操作和更多的搜索操作要求,Arraylist将是你最好的选择。
其他回答
嗯,我猜数组列表可以用在以下情况下:
您无法确定将会出现多少个元素 但是您需要通过索引随机访问所有元素
例如,您需要导入并访问联系人列表中的所有元素(您不知道其大小)
1)如上所述,与ArrayList(O(n))相比,在LinkedList中插入和删除操作具有良好的性能(O(1))。因此,如果应用程序需要频繁的添加和删除,那么LinkedList是最好的选择。
2)搜索(get方法)操作在Arraylist (O(1))中是快速的,但在LinkedList (O(n))中不是,所以如果有更少的添加和删除操作和更多的搜索操作要求,Arraylist将是你最好的选择。
如果您需要在中间插入项,并且不想开始调整数组大小和移动内容,则列表的优势就会显现出来。
你是对的,通常情况下并非如此。我遇到过一些非常具体的案例,但不是很多。
这完全取决于你在迭代时所做的操作类型,所有数据结构都在时间和内存之间进行权衡,我们应该根据需要选择正确的DS。有些情况下,LinkedList比数组快,反之亦然。考虑数据结构上的三个基本操作。
搜索
由于array是基于索引的数据结构,搜索array.get(index)将花费O(1)时间,而linkedlist不是索引DS,因此您将需要遍历到index,其中index <=n, n是链表的大小,因此array在随机访问元素时比链表更快。
那么,这背后有什么好处呢?
As Arrays are contiguous memory blocks, large chunks of them will be loaded into the cache upon first access this makes it comparatively quick to access remaining elements of the array,as much as we access the elements in array locality of reference also increases thus less catch misses, Cache locality refers to the operations being in the cache and thus execute much faster as compared to in memory,basically In array we maximize the chances of sequential element access being in the cache. While Linked lists aren't necessarily in contiguous blocks of memory, there's no guarantee that items which appear sequentially in the list are actually arranged near each-other in memory, this means fewer cache hits e.g. more cache misses because we need to read from memory for every access of linked list element which increases the time it takes to access them and degraded performance so if we are doing more random access operation aka searching , array will be fast as explained below.
插入
这是简单和快速的LinkedList的插入是O(1)操作在LinkedList (Java)阵列相比,考虑数组充满的情况下,我们需要将内容复制到新数组如果数组完全使一个元素插入ArrayList O (n)在坏的情况下,而ArrayList还需要更新其指数年底如果你插入一些除了数组,链表的我们不必调整它,你只需要更新指针。
删除
它的工作原理类似于插入,在LinkedList中比在array中更好。
使用链表对数组和多项式操作进行基数排序。
推荐文章
- 如何读一个文本文件到一个列表或数组与Python
- Linq选择列表中存在的对象(A,B,C)
- 如何在Python中将十六进制字符串转换为字节?
- 返回大列表中每n项的python方式
- 与push()相反;
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Python:查找列表中的元素
- 使arrayList.toArray()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- 如何将字典列表合并为一个字典?
- .Net数据结构:ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary—速度,内存,以及何时使用每个?
- 在Python中创建一个初始容量的列表
- 如何排序一个数组列表在Java
- 在$.ajax()中将数组传递给ajax请求