30C. 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;
    }
  };

The List type

Technically, an abstract data type needs to have a type name associated with it. We could call it List. But for our purposes, it is probably better to make it clear that a list is represented by a pointer, so we will use type ListCell* for a list.

Exercises

  1. Draw a linked list diagram of conceptual list [4]. There should be exactly one list cell in your diagram. Now write a C++ statement that defines variable 'four', of type List, to be that linked list. Answer

  2. Draw a linked list diagram of conceptual list [2, 4]. There should be exactly two list cells in your diagram. Now write a C++ statement that defines variable 'twofour', of type List, to be that linked list. Answer