![]() |
VOOZH | about |
A singly linked list is a linear data structure where each node stores data and a pointer to the next node in the sequence. It allows dynamic memory usage and efficient insertion or deletion of elements.
Example:
10 -> 20 -> 30 -> NULL
Here, each node points to the next node, and the last node points to NULL.
To represent a singly linked list as a class, we need to first define a Node type that represents a single node.
class Node {
int data;
Node* next;
}
We then define the class that contains the pointer to the head of the linked list as data member and all basic operation functions. For now, we will only include the insertAtHead() and print() function for simplicity.
class LinkedList {
Node* head;
public:
void insertAtHead(){ ... }
void print() { ... }
}
We can add more functions such as accessing element at particular position, search and delete operations, etc. according to our requirements.
To know how to insert element at head and print linked list, refer to the following articles:
Implementing data structures like linked lists is fundamental for developing efficient applications.
Example: Program to implement singly linked list using a class
Elements of the list are: 1 2 3 4
The program creates a singly linked list using two classes: Node and LinkedList.
Example: If we insert 1, 2, 3, and 4 using insertAtHead(), the linked list becomes: 1 -> 2 -> 3 -> 4
The print() function visits each node one by one and displays the data.
A singly linked list can also perform operations like searching and deleting nodes.
The search operation traverses the linked list from the head node until the required value is found.
Example: To search for 3 in: 1 -> 2 -> 3 -> 4
The traversal checks nodes one by one until node 3 is found.
The delete operation removes a node from the linked list by changing the links between nodes.
Example: Deleting 3 from: 1 -> 2 -> 3 -> 4
Results in: 1 -> 2 -> 4