How to Create Linked List in C++: Syntax and Example
To create a linked list in C++, define a
struct or class for the node containing data and a pointer to the next node. Then, create nodes dynamically and link them by setting the next pointers to build the list.Syntax
A linked list node typically has two parts: data to store the value, and a pointer to the next node. You define it using a struct or class like this:
data: holds the value (e.g., int, string)next: pointer to the next node ornullptrif last
cpp
struct Node {
int data; // stores the value
Node* next; // pointer to the next node
};Example
This example creates a simple linked list with three nodes holding values 10, 20, and 30, then prints them in order.
cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
int main() {
// Create nodes
Node* head = new Node{10, nullptr};
Node* second = new Node{20, nullptr};
Node* third = new Node{30, nullptr};
// Link nodes
head->next = second;
second->next = third;
// Traverse and print
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
// Free memory
delete third;
delete second;
delete head;
return 0;
}Output
10 20 30
Common Pitfalls
Common mistakes when creating linked lists include:
- Not initializing the
nextpointer tonullptr, causing undefined behavior. - Forgetting to link nodes properly, so the list breaks.
- Not freeing allocated memory, causing memory leaks.
- Accessing nodes after deleting them.
Always set next to nullptr for the last node and delete all nodes when done.
cpp
/* Wrong: next pointer not set, leads to garbage */ Node* node = new Node{5}; // next is uninitialized /* Right: next pointer set to nullptr */ Node* node = new Node{5, nullptr};
Quick Reference
- Define a
Nodestruct/class with data and next pointer. - Create nodes dynamically using
new. - Link nodes by setting
nextpointers. - Traverse using a loop until
nullptr. - Delete nodes to free memory.
Key Takeaways
Define a node with data and a pointer to the next node to build a linked list.
Always initialize the next pointer to nullptr to avoid errors.
Link nodes by setting the next pointer to the following node.
Traverse the list by moving from node to node until nullptr is reached.
Free all allocated nodes with delete to prevent memory leaks.