Linked Lists

What is a linked list?

A linked list is a dynamic data structure that store item in nodes.

Arrays can mimic this but they essentially create copies of themselves with new dimensions when resizing 

Nodes

Each node in a linked list has a pointer which points to the address of the next node.  Each element of a linked list is called a node.

The start of a linked list is called the HEAD and the last element points to the NULL.  Each node has its own address in memory, and stores the data item and a pointer to the next node. The following diagram represents a node.

Example Single Linked List

A simple example of a single linked list with four nodes is shown below. The four node linked list stores the words ‘Computing’, ‘Science’, ‘is’, and 'fun'.

Single Linked List

Points to note about Linked Lists

Single Linked List Operations - Inserting

To insert new data into the list, for example inserting the word ‘really’ between ‘is’ and ‘fun’.

Comparison - Before and After

Single Linked List Operations - Deleting

To remove data from the list, for example removing the word ‘Science’

Comparison - Before and After

Linked List Operations

The pointer of the last node will have to point to the newly created node.

When a new node is added then the pointer of the previous node has to be amended to point to the new node and the new node has to point to the node that was previously next in the list.

The pointer of the previous node before the item to be deleted will be amended to point to the next item in the list.

Each node has to be visited and the pointer followed to the address of the next node.

What is a double linked list?

A double linked list is very similar to a single linked list, but has an additional pointer in each node that stores the address of the previous node. This means the list can be traversed in both directions.

The following diagram represents a node in a double linked list.

Example Double Linked List

As there is an extra pointer in each node it can store the address f the previous and the next node.

Double Linked List Operations - Inserting a new Node

To insert new data into the list, for example inserting the word ‘really’ between ‘is’ and ‘fun’

Comparison - Before and After

Double Linked List Operations - Deleting a Node

To remove data from the list, for example removing the word ‘really’

Comparison - Before and After

Types of Linked Lists: Summary

Single - Nodes have a data item as well as a pointer to the next field. The last node will contain a NULL pointer.

Double/Doubly - This is when each node will have a pointer to the next AND previous nodes.

Advantages and Disadvantages vs Arrays

Advantages

Disadvantages