Singly Linked List
A unidirectional linear data structure
Introduction
A Singly linked list is a linear data structure, it consists of nodes where each node contains a data field and a pointer to the next node in the sequence. The last node points to null
, marking the end of the list. It is memory-efficient and supports efficient insertion and deletion operations, especially at the beginning or middle, as no shifting of elements is required.
Visualization of Singly Linked List
Operation on Singly Linked List
Insertion
Deletion
Traversal
-
Initialize a pointer (
current
) to the head of the list. -
While (
current!=null
)
-
Process the data of the current node.
-
Move the pointer to the next node (
current = current->next
).
- The traversal stops when all nodes are processed.
// traversalonll.c
void traverseLinkedList(struct Node* head)
{
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
Searching
- Start from the head of the linked list.
- Check if the current node's data matches the target value:
- If a match is found, return
true
.
- Move to the next node.
- Repeat steps 2 and 3 until:
- The target value is found (return
true
). - The end of the list is reached (return
false
).
//searchingonll.c
bool searchLinkedList(struct Node* head, int target)
{
while (head != NULL) {
if (head->data == target) {
return true; // Value found
}
head = head->next;
}
return false;
}