CS110, Architecture and Operating Systems

Indexing Lists Using Arrays

In CS 70, you created linked lists using C++ pointers. However, there is another way to implement a linked list (or anything else that uses pointers), which is to use array indices instead of the next pointer.

There are two ways to understand this technique:

  1. Think of a pointer as a way to locate a piece of information. Similarly, an array index is just a way to find a piece of information.
  2. You now know enough to realize that computer memory is just a big array of bytes, and any memory address is just an index into that array. So a pointer is like an array index. There is no law that says the pointer has to be relative to memory location 0; it could equally well be relative to the beginning of some array you allocated.

So if you have an array of Nodes:

    struct Node {
        int data;
        int next;
    };

    Node stuff[20];
and the current node in your list is stuff[0], then you could access the data in the next node in your list with:
    int nextNode = stuff[0].next;
    int nextData = stuff[nextNode].data;

Last modified April 6, 2002 by geoff@cs.hmc.edu