为什么有人想要使用链表而不是数组?

毫无疑问,编码一个链表比使用数组要多一些工作,人们可能会想知道如何才能证明这些额外的工作是合理的。

我认为在链表中插入新元素是微不足道的,但在数组中这是一个主要的任务。与将数据存储在数组中相比,使用链表存储一组数据还有其他优点吗?

这个问题不是这个问题的重复,因为另一个问题是专门问一个特定的Java类,而这个问题是关于一般数据结构的。


当前回答

首先,在c++中,使用链表应该不会比使用数组更麻烦。对于链表,可以使用std::list或boost指针列表。链表与数组的关键问题是指针需要额外的空间和糟糕的随机访问。你应该使用链表,如果你

你不需要随机访问数据 您将添加/删除元素,特别是列表中间的元素

其他回答

It's easier to store data of different sizes in a linked list. An array assumes every element is exactly the same size. As you mentioned, it's easier for a linked list to grow organically. An array's size needs to be known ahead of time, or re-created when it needs to grow. Shuffling a linked list is just a matter of changing what points to what. Shuffling an array is more complicated and/or takes more memory. As long as your iterations all happen in a "foreach" context, you don't lose any performance in iteration.

当集合不断增加和减少时,链表尤其有用。例如,很难想象尝试使用数组实现一个Queue(添加到末尾,从前面删除)—您将花费所有时间向下移动内容。另一方面,对于链表来说,这是微不足道的。

首先,在c++中,使用链表应该不会比使用数组更麻烦。对于链表,可以使用std::list或boost指针列表。链表与数组的关键问题是指针需要额外的空间和糟糕的随机访问。你应该使用链表,如果你

你不需要随机访问数据 您将添加/删除元素,特别是列表中间的元素

Arrays make sense where the exact number of items will be known, and where searching by index makes sense. For example, if I wanted to store the exact state of my video output at a given moment without compression I would probably use an array of size [1024][768]. This will provide me with exactly what I need, and a list would be much, much slower to get the value of a given pixel. In places where an array does not make sense there are generally better data types than a list to deal with data effectively.

我将添加另一个-列表可以充当纯函数式数据结构。

例如,您可以让完全不同的列表共享相同的结束部分

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中。

这就是为什么它们在函数式语言中如此受欢迎的原因,函数式语言使用不可变变量——前置和尾部操作可以自由发生,而无需复制原始数据——当您将数据视为不可变时,这是非常重要的特性。