24C. Linked Lists


Linked lists

Our goal is implement conceptual lists in C++. It is not possible to add notation [2, 4, 6], since we cannot add new notation to C++. But we can add functions and a type. On this page we just look at how lists are represented. Functions are defined on the next page.


Representation

We need to choose a way to represent the information in a list. We use a linked representation, where a linked list contains one list cell (a structure) for each of its members, and the cells are linked to one another by pointers. The last cell in the linked list holds a null pointer that indicates the end of the list. Here is a linked list diagram of list [2, 4, 6] showing three list cells.

Each cell has type ListCell, defined as follows.

  struct ListCell
  {
    ListCell* tail;
    int       head;

    ListCell(int h, ListCell* t)
    {
      head = h;
      tail = t;
    }
  };


Types List and ConstList

An abstract data type needs to have a type associated with it. Let's call that type List. When you see a variable of type List, you usually think of it in conceptual terms, simply as a list of integers.

But C++ requires a list to have a physical representation, which we have seen above. So we need to be able to think of a list in physical terms when we need to. At the physical level, a list is a pointer to a ListCell. Here is a C++ definition of type List.

  typedef ListCell* List;

C++ allows fields of structures to be changed and, because there are no restrictions on it, a pointer of type List can be used to change a ListCell. We will also want a type of list that cannot be changed, to take away opportunities to change things that should be left alone. Here is a C++ definition of type ConstList, which plays that role.

  typedef const ListCell* ConstList;