This question mentions that it is possible to go about implementing a linked list within an array.
Whilst I can imagine how to do this with multiple arrays, how can it be done with a single array?
EDIT: Can this done be efficiently considering that items will need to be removed & inserted from the list - presumably requiring identification of free elements in the array?
You could use a fixed-size memory block allocator where each block has a next-pointer pointing to the next element in the linked list.
A good and simple implementation is from the Contiki operating system (BSD license), see implementation of memb and list.
You use them like this:
Edit: Sorry, you did not mention any particular programming language and I'm mostly familiar with C and C++. If you can decipher how
memb
andlist
is implemented then the basic theory should be the same: A simple block allocator keeping track of free/used blocks, and a linked list implementation that can refer to these individual blocks.You could (for example) have a linked-list of integers by putting your first data item in the element of the array, and the index of the next item in the second element. This would restrict you to storing types that were compatible with/convertible to an index.
If it is an array of objects, then each object would store a value and a pointer to the next object.
So here I have 2 linked lists, the first one:
"a" -> "b" -> "c" -> "d" -> "e"
and the second one:
"1" -> "2" -> "3" -> "4"
both using an index of -1 as the end of the list.
Then you would need multiple pointers (one for each list) to determine where you are in the list.
Honestly, I'm not even sure I understand the question, but wanted to throw out ideas anyway.
In C++ I quickly wrote this and it works. Each index in the array contains a doubly linked list.
output:
Here is a possible approach(using C++): your node would be consisted of indexes to the next and previous elements in the list:
where
next
andprev
will hold indexes of the array storing theLink
s.additionally, there should be a mechanism accounting for the available elements in the array, the more naive implementation could be:
you would need functions to get you an index from
bool available
(indicating no node at index,i
inhead
, where the element ofavailable
has a valuetrue
). For example:Here is how
puch_back()
could look like:Additionally there should be a function reverse to
get_available_index()
in whichavailable[i]
element is set totrue
(and object is destroyed(head + i)->~Link();
?)Is far as I can understand there will be fragmentation, reflected in the values stored in the
bool
array, which will affect only the time it takes to store a new node.