Single Linked List Implementation
A linked list is a linear data structure that includes a series of connected nodes which are randomly stored in the memory.
Here, each node stores the data and the address of the next node. A node contains two fields i.e. data stored at that particular address and the pointer which contains the address of the next node in the memory. The last node of the list contains pointer to the null.
You have to start somewhere, so we give the address of the first node a special name called HEAD. Also, the last node in the linked list can be identified because its next portion points to NULL.
Linked lists can be of multiple types: singly, doubly, and circular linked list. In this article, we will focus on the singly linked list.
Types of Linked List :
There are 3 types of linked list such as:-
- Single Linked List
- Doubly Linked List
- Circular 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.
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 *));
Traversal:
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.
In the following example we are going to see the creation of node in a single linked list and its traversal using structure in C.