在c中分配一个连续的链表
我正在尝试在 c 中创建一个链接列表。不同的是,我想为列表分配内存,以便所有节点都连续存储在内存中。 也许数组结构是可行的方法。 有什么想法吗?
Im trying to create a linked list in c. The twist is that I want to allocate the memory for the list so that all the nodes are consecutively stored in memory.
Maybe an array structure is the way to go.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,使用数组。更有趣的是你为什么想要这个。如果您的程序需要此功能才能工作,那么您需要确保您的数组足够大以存储可能分配的所有节点。如果没有,您可以批量分配节点。
供参考。我过去见过这种策略,假设在搜索列表时顺序分配的节点会导致更少的缓存未命中。在我们感兴趣的系统中,这实际上并没有带来太大的性能改进。 [当然,分析还不够!]
Yes, use an array. More interesting is why you want this. If your program requires this to work, then you'll need to make sure your array is big enough to store all the nodes that might be allocated. If not, you can allocate batches of nodes.
FYI. I've seen this strategy used in the past on the assumption that sequentially allocated nodes would result in fewer cache misses when searching the list. In the system of interest, that didn't actually give much a performance improvement. [ Not enough profiling of course!.]
你可以这样做,
这将为连续位置的链表结构分配空间。
You could do something like this
This would allocate space for linked list structure in contiguous locations.
最明显的方法是在一个块中分配多个节点,然后将它们链接到一个空闲列表中。当您需要向链接列表添加一个节点时,您将从空闲列表的头部获取该节点。当你想删除一个节点时,你可以将它链接回空闲列表:
The obvious way would be to allocate a number of nodes in a block, then link them together into a free list. When you need to add a node to your linked list, you'll grab the one from the head of your free list. When you want to delete a node, you link it back onto the free list:
如果您正在查看链接列表,请不要担心它们在内存中的位置。这就是节点上的指针的用途。
如果您希望它们是连续的,请分配一个数组。
If you're looking at a linked list, don't worry about where in memory they are. That's what the pointers on the nodes are for.
If you want them sequential, allocate an array.