0

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
  • 1
    You need an array of structs with two ints that are the prev and next indexes. Commented Jan 31, 2019 at 15:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

(or, for efficiency reasons, do not use array entry 0 so zero means "no next" or "no prev".)
@PaulOgilvie I thought of that, but it wastes an entry for probably marginal or zero gains in speed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.