The linked list

Before moving onto the main topic for this week, object-oriented programming, we will start with a look at a further data structure, linked lists. Linked lists, which are different to the plain lists we discussed above, are unlike arrays in that they are not stored continuously in memory. Instead, data is stored as a series of linked nodes. Each node contains one item of data, and links to the memory locations of the previous and the next item of data in the linked list.

Linked list diagram

Each node has a link to the previous and the following node. When we add a new item of data, we make the previous node link to the new node, and we link the new node back to the previous node to form a two-way link.

The first node in the list links to nothing in the reverse direction (indicated in Python by the special value None) and similarly, the final node in the list links to nothing in the forward direction.

In addition, a linked list contains two variables pointing to the first node and the last node. This means that we can always access the start of the linked list and the end of the linked list very quickly and efficiently.

We will now think about the consequences of this.