Adding a node at the beginning of a singly linked list
If you have been learning about Linked Lists, this is the fun and easy part. Adding nodes. Adding nodes means getting to store data in memory.
A node uses the struct construct. Something that looks like this.
/**
* struct node - node structure
* @value: integer stored by node
* @next: pointer to the next node
* Description: Node is used for a
* Linked list
*/
typedef struct node
{
int value;
struct node *next;
} node;
See how simple this is. I presume that you have knowledge of structs and pointers.
After defining our node. It is time to use it! So, let us add a node at the beginning of the list and ensure that each time, we a node is added, it goes to the beginning of the list
We shall accomplish this using a function.
void add_node_front(node **head, int value);
After defining the function. Now let us write it, then call it in the main function.
#include "main.h"
#include <stdio.h>
#include <stdlib.h>
/**
* add_node_front - adds node to the front of the
* list
* @head: pointer to the head node
* @value: value to be added to the struct
* Return: void
*/
void add_node_front(node **head, int value)
{
node *newNode;
newNode = malloc(sizeof(node));
if (newNode == NULL)
printf("Memory Allocation failed\n");
newNode->value = value;
newNode->next = *head;
*head = newNode;
}
I have used a header file called main.h to store all my functions. Now, here is our main file so that we can call our function.
#include <stdio.h>
#include "main.h"
/**
* main - example to show how nodes work
* Return: 0 always success
*/
int main(void)
{
node *head;
head = NULL;
add_node_front(&head, 22);
add_node_front(&head, 36);
while (head != NULL)
{
printf("Value = %d\n", head->value);
printf("Current memory location = %p\n",(void *)head);
printf("Next memory location = %p\n",(void *)head->next);
head = head->next;
}
return (0);
}
This function adds a node at the beginning of your node. If you want to learn how to add a node at the end of the list, here is an article explaining it with an example. Happy learning.