Linked list is an important data structure. Linked list is a linear data structure just like array but its internal working and memory management are completely different. Today we will see the basic operations of linked list.
What is Linked List ?
Linked list is a method of storing data, different data like (number, text etc.) are stored in different nodes. These nodes store the data of their own node and store the address of other nodes through which we can access the data of other nodes very easily.
A node is made up of two parts:
- Data: Holds any value such as: 5, 10, “Hello”
- Next: This is a pointer that stores the address of the next node.
The node at the end of the program does not point to the address of any node, so NULL means zero.
Basic Operation of Linked List
- Insertion: Add New Node.
- Deletion: Deleting existing nodes
- Search: Search a Specific Node.
- Traversal: Show the Full List Return.
1. Inseration
- Insert Node at the Beginning.
- Insert Node at the End.
- Insert Node After a given Node.
Example: Insert Node at the Beginning
10 -> 20 -> 30 -> NULL We want to add 5 values to it at the beginning. Step:-
- We will create a node with
data = 5. - We will point the
nextpointer of the new node to the currenthead. - We will update the head to point to the new node.
List after insert: 5 -> 10 -> 20 -> 30 -> NULL
2. Deletion
We can delete data in a linked list in three ways:
- Delete First Node.
- Delete Last Node.
- Delete Specific Node.
Example: Delete Specific Node
5 -> 10 -> 20 ->30 -> NULL
Suppose we want to delete the node 20 above.
- I will find the node 10 before 20.
- I will point the next pointer of 10 to the next pointer of 20 to 30.
- To delete the 20th node from memory, we will use the free() function or delete
3. Search
You have created a linked list and want to search for a value from that linked list. Below is a step-by-step guide on how to do it.
Example:
5 -> 10 -> 30 -> NULLSuppose you are looking for 30 people.
Step:
- I’ll start from the head.
- We will compare the data of each node with 30.
- If it matches, I will return the found item.
- If it doesn’t find even NULL, it will return Not Found.
4. Traversal
This operation will visit each node in the list once and print the data contained in that node.
Example:
List:5 -> 10 -> 30 -> NULL
Step:
- Create a pointer named
currentand place it in the head. - Will print
current->datauntil current is NULL and move current tocurrent->next.
