Definition
A linked list is a linear data structure where elements, called nodes, are stored in separate memory locations and connected using pointers. Each node contains two parts:
- Data: The value stored in the node.
- Pointer: A reference to the next node in the sequence.
- Define the Node Structure:
- Create Nodes and Link Them:
- Traverse and Print the List:
- A linked list stores elements in nodes connected by pointers, allowing dynamic memory allocation.
- In C++, linked lists are implemented using structs/classes and pointers.
- Linked lists enable efficient insertion and deletion but require extra memory for pointers.
Unlike arrays, linked lists allow efficient insertion and deletion of elements without shifting other elements.
Implementation in C++
A simple singly linked list in C++ uses a struct to define a node and pointers to connect nodes.
Step-by-Step Example
Goal: Create a linked list with three nodes containing the values 10, 20, and 30.
``cpp`
struct Node {
int data;
Node next;
};
`cpp
Node head = new Node();
Node second = new Node();
Node third = new Node();
head->data = 10;
head->next = second;
second->data = 20;
second->next = third;
third->data = 30;
third->next = nullptr;
`
`cpp``
Node* current = head;
while (current != nullptr) {
std::cout data next;
}
// Output: 10 20 30
Diagram
Suppose the list is:
$$ \text{head} \longrightarrow [10|\cdot] \longrightarrow [20|\cdot] \longrightarrow [30|\text{nullptr}] $$