27B. Linked Lists


Linked lists

Our goal here 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.


Representation

The first issue is how to represent the information in a list. We use a linked representation, where a linked list contains one list cell 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. Here is a linked list diagram of list [2, 4, 6].

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

Since a list is always a pointer to a ListCell, it is convenient to make two additional type definitions.

  typedef ListCell* List;
  typedef const ListCell* ConstList;