Linked lists in C
What are linked lists? Linking lists is one of the many uses of pointers in programming. Before going through this article, you should ensure that you have at least some background on how pointers work in C language. Linked lists are a type of data structure that consists of a series of nodes that are connected. Each node consists of data and the address to the next node. The head node contains the address to the next node and the address value in the last node is null.
As mentioned earlier, linked lists are of type struct which allows them to store different types of variables and pointers. We can declare the structure of a node as follows;
struct node
{
int n; //data stored
struct node *next; //adress of the next node
};
How do we create a singly linked list?
Different nodes within a list are interconnected to each other using pointers. Say you need to create a new node on your list. You will start by declaring and initializing the head pointer to 0, and a new node pointer whose size will be allocated as follows:
struct node *head, *newnode *temp;head = 0;newnode = (struct node *)malloc(sizeof(struct node));//size of the node
newnode->next = 0; //assign the next node adress to 0
A condition has to be established that as long as the head pointer is not equal to zero, a new node should be formed and linked as shown below;
if(head == 0)
{
head = temp = newnode;//assign new node address to head if head = 0
}
else {
temp->next = newnode;
temp = newnode;
}
Linked lists have many applications and several examples will be useful in understanding how they work. In the next blog, we will see how to insert, delete and shuffle elements of a playlist using this data structure.