Operations on Single Linked List
Single Linked List :
Singly linked list is the most common linked list among the others. The singly linked list can be traversed only in one direction. It is a collection of ordered sets of elements. In singly linked list, Each node has a data and a pointer to the next node.
Algorithm
Construction of a single linked list :
For constructing a singly linked list in C we make use of the structure keyword(struct), for creating user-defined data types, which can store various different types of data in the nodes of the singly linked list.
Operations on a single linked list:
Node creation:
Following is how we create a node for a linked list using structure in C:
struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node *));
Insertion:
The insertion into a singly linked list can be performed at different positions. Based on the position of the new node being inserted, the insertion is categorized into the following categories.
- Insertion at beginning - It involves inserting any element at the front of the list. We just need to a few link adjustments to make the new node as the head of the list.
- Insertion at end of the list - It involves insertion at the last of the linked list. The new node can be inserted as the only node in the list or it can be inserted as the last one. Different logics are implemented in each scenario.
- Insertion after specified node - It involves insertion after the specified node of the linked list. We need to skip the desired number of nodes in order to reach the node after which the new node will be inserted.
Deletion and Traversal:
The Deletion of a node from a singly linked list can be performed at different positions. Based on the position of the node being deleted, the operation is categorized into the following categories.
- Deletion at beginning - It involves deletion of a node from the beginning of the list. This is the simplest operation among all. It just need a few adjustments in the node pointers.
- Deletion at the end of the list - It involves deleting the last node of the list. The list can either be empty or full. Different logic is implemented for the different scenarios.
- Deletion after specified node - It involves deleting the node after the specified node in the list. we need to skip the desired number of nodes to reach the node after which the node will be deleted. This requires traversing through the list.
- Traversing - In traversing, we simply visit each node of the list at least once in order to perform some specific operation on it, for example, printing data part of each node present in the list.
- Searching - In searching, we match each element of the list with the given element. If the element is found on any of the location then location of that element is returned otherwise null is returned.
In the following example we are going to see the above operations on a single linked list using structure in C.