为什么有人想要使用链表而不是数组?
毫无疑问,编码一个链表比使用数组要多一些工作,人们可能会想知道如何才能证明这些额外的工作是合理的。
我认为在链表中插入新元素是微不足道的,但在数组中这是一个主要的任务。与将数据存储在数组中相比,使用链表存储一组数据还有其他优点吗?
这个问题不是这个问题的重复,因为另一个问题是专门问一个特定的Java类,而这个问题是关于一般数据结构的。
为什么有人想要使用链表而不是数组?
毫无疑问,编码一个链表比使用数组要多一些工作,人们可能会想知道如何才能证明这些额外的工作是合理的。
我认为在链表中插入新元素是微不足道的,但在数组中这是一个主要的任务。与将数据存储在数组中相比,使用链表存储一组数据还有其他优点吗?
这个问题不是这个问题的重复,因为另一个问题是专门问一个特定的Java类,而这个问题是关于一般数据结构的。
当前回答
我将添加另一个-列表可以充当纯函数式数据结构。
例如,您可以让完全不同的列表共享相同的结束部分
a = (1 2 3 4, ....)
b = (4 3 2 1 1 2 3 4 ...)
c = (3 4 ...)
例如:
b = 4 -> 3 -> 2 -> 1 -> a
c = a.next.next
不需要把a指向的数据复制到b和c中。
这就是为什么它们在函数式语言中如此受欢迎的原因,函数式语言使用不可变变量——前置和尾部操作可以自由发生,而无需复制原始数据——当您将数据视为不可变时,这是非常重要的特性。
其他回答
使用链接列表的人必须阅读。人们会再次爱上数组的。 它谈到了 无序执行,硬件预取,内存延迟等。
http://www.futurechips.org/thoughts-for-researchers/quick-post-linked-lists.html
假设您有一个有序集,您还想通过添加和删除元素来修改它。此外,您需要能够以这样的方式保留对元素的引用,以便稍后可以获得前一个或下一个元素。例如,一本书中的待办事项列表或一组段落。
首先,我们应该注意到,如果您想在集合本身之外保留对对象的引用,那么您可能最终会将指针存储在数组中,而不是存储对象本身。否则你将无法插入到数组中-如果对象嵌入到数组中,它们将在插入期间移动,并且任何指向它们的指针都将无效。数组下标也是如此。
您的第一个问题,正如您自己所注意到的,是插入链表允许插入O(1),但数组通常需要O(n)。这个问题可以部分克服——可以创建一种数据结构,提供类似数组的按顺序访问接口,其中读和写在最坏的情况下都是对数的。
Your second, and more severe problem is that given an element finding next element is O(n). If the set was not modified you could retain the index of the element as the reference instead of the pointer thus making find-next an O(1) operation, but as it is all you have is a pointer to the object itself and no way to determine its current index in the array other than by scanning the entire "array". This is an insurmountable problem for arrays - even if you can optimized insertions, there is nothing you can do to optimize find-next type operation.
首先,在c++中,使用链表应该不会比使用数组更麻烦。对于链表,可以使用std::list或boost指针列表。链表与数组的关键问题是指针需要额外的空间和糟糕的随机访问。你应该使用链表,如果你
你不需要随机访问数据 您将添加/删除元素,特别是列表中间的元素
对我来说是这样的,
Access Linked Lists allow only sequential access to elements. Thus the algorithmic complexities is order of O(n) Arrays allow random access to its elements and thus the complexity is order of O(1) Storage Linked lists require an extra storage for references. This makes them impractical for lists of small data items such as characters or boolean values. Arrays do not need an extra storage to point to next data item. Each element can be accessed via indexes. Size The size of Linked lists are dynamic by nature. The size of array is restricted to declaration. Insertion/Deletion Elements can be inserted and deleted in linked lists indefinitely. Insertion/Deletion of values in arrays are very expensive. It requires memory reallocation.
为什么有人想要使用链表而不是数组?
这只是一个原因——如果你需要一个链表数据结构,而你所使用的编程语言不支持指针。