The LinkedList class implements a simple version of a Single LinkedList, a collection of elements formed by a series of nodes that allows for very efficient adding and removing of elements.
The class uses Templates to be able to contain any type of object or basic types.
Each node contains an element and a reference to the next node. In this way, it is possible to add or remove elements by creating or deleting nodes, and managing the references between them.
The class has functions to get, add, insert, replace, and remove elements from the LinkedList. Getting an element is a relatively slow process compared to a simple array, because it is necessary to traverse all the nodes until reaching the desired node.
To improve efficiency, the class maintains a reference to the last accessed element. This avoids having to traverse the collection from the beginning, which is especially useful when accessing the same index repeatedly.
Additionally, the class maintains a reference to the head and tail nodes, which allows for efficient implementation of LIFO (Stack) and FIFO (Queue) type structures.
There are also methods available to search for elements within the LinkedList, reverse the elements, and to copy the elements to and from an external array.
For more information, see the entry Implementing a Linked List in Arduino.
User Manual
Constructor
The LinkedList class is instantiated through its constructor.
// Create a new LinkedList
LinkedList();
General methods
// Get the size
int GetSize() const;
Access elements
// Returns the first element
T GetHead();
// Returns the last element
T GetTail();
// Returns the element at the specified position
T GetAt(int index);
Insert elements
// Insert an element at the beginning
void InsertHead(T);
// Insert an element at the end
void InsertTail(T);
// Insert an element at the specified position
void InsertAt(int index, T);
Replace elements
// Replace the first element
void ReplaceHead(T value);
// Replace the last element
void ReplaceTail(T value);
// Replace the element at the specified position
void ReplaceAt(int index, T value);
Remove elements
// Remove all elements
void Clear();
// Remove the first element
T RemoveHead();
// Remove the last element
T RemoveTail();
// Remove the element at the specified position
T RemoveAt(int index);
Conversion to arrays
// Returns all elements in a new array
T* ToArray();
// Initializes the LinkedList by copying the elements from an array
void FromArray(T* fromArray, int n);
Examples
The LinkedList library includes the following examples to illustrate its use.
- LinkedList: General example of using the LinkedList class
Installation
- Download the latest version from GitHub
- Unzip the file
- Copy to your library folder (usually My Documents\Arduino\libraries)
- Restart the Arduino IDE
Download the code
All the code in this post is available for download on Github.