LEARNING OUTCOME 6
Linked List
A linked list is a linear data structure where elements are not stored in contiguous memory locations. Instead, each element, called a node, contains data and a pointer to the next node in the sequence. This allows for dynamic memory allocation and efficient insertion and deletion of elements, especially when compared to arrays.
Array-based List vs. Linked List
Feature | Array-Based List | Linked List |
---|---|---|
Memory Allocation | Contiguous memory allocation | Dynamic memory allocation |
Access to Elements | Direct access using index (O(1)) | Sequential access through pointers (O(n)) |
Insertion and Deletion | Inefficient (O(n)), requires shifting elements | Efficient (O(1)) if pointer to node is known |
Space Overhead | Minimal overhead | Additional memory for pointers |
Flexibility in Size | Fixed size | Dynamic size |
Cache Efficiency | Generally more cache-friendly | Less cache-friendly due to non-contiguous memory |
Types of Linked Lists
- Singly Linked List: Each node contains data and a pointer to the next node. It allows traversal in one direction only, from the head to the tail.
- Doubly Linked List: Each node contains data, a pointer to the next node, and a pointer to the previous node. This allows traversal in both directions.
- Circular Linked List: The last node points back to the first node, forming a circular structure. This can be useful for certain algorithms and data structures.
Creating a Linked List
Defining the Node Structure
The fundamental building block of a linked list is the node. Each node contains:
- data: The actual data stored in the node (can be any data type).
- next: A pointer to the next node in the list. This pointer is what links the nodes together.
2
3
4
5
6
7
The LinkedList Class
To manage the linked list, it's good practice to create a `LinkedList` class. This class will encapsulate the operations you can perform on the list and hold a pointer to the first node (the `head`).
2
3
4
5
6
7
8
Linked List Operations
Traversing and Displaying
To see the contents of the list, you traverse it from the `head`, following the `next` pointers until you reach `nullptr`.
2
3
4
5
6
7
8
Insertion
Nodes can be inserted at the beginning, middle, or end of the list.
Inserting at the Beginning
2
3
4
5
Inserting at the End
2
3
4
5
6
7
8
9
10
11
12
Deleting a Node
To delete a node, you must find it and then adjust the `next` pointer of the *previous* node to bypass the node being deleted.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Memory Management
It is crucial to deallocate memory for each node when the list is no longer needed to prevent memory leaks. This is typically done in the class destructor.
2
3
4
5
6
7
8
9