I need a way to implement a doubly linked list using only an array and no pointers in C. There's is a mention of this in Thomas Cormen but I can't think of a way to actually implement it.
1 Answer
Instead of using pointers which, in C, are usually numbers that index into the address space, use integer indexes into your array as references to the previous and next members e.g.
struct Element
{
int next;
int prev;
// Any data you want for this element in the list
};
struct Element array[MAX_ELEMENTS];
Then for the element at index i in the array, the next element in the list is
array[array[i].next]
and the previous element is
array[array[i].prev]
Instead of using NULL to mean a null pointer, use -1 to mean a "null" index.
2 Comments
Paul Ogilvie
(or, for efficiency reasons, do not use array entry 0 so zero means "no next" or "no prev".)
JeremyP
@PaulOgilvie I thought of that, but it wastes an entry for probably marginal or zero gains in speed.