Adding a node to a Singly Linked List
Today I will show you how to add a node to a linked list. But before doing much, let's make sure you have an understanding of a Linked List.
According to ChatGPT,
A linked list is a fundamental data structure in computer science used to organize and store a collection of elements, often referred to as nodes. Unlike arrays, which use a contiguous block of memory to store elements, linked lists consist of nodes where each node contains two parts: the data or value, and a reference (or link) to the next node in the sequence.
I will use C Language to demonstrate adding nodes to a list.
A node is defined as a struct. Like this:
/**
* struct node - node for the linked list
* @value: value of int
* @next: next pointer
* Description: This is a simple node
*/
typedef struct node
{
int value;
struct node *next;
} node;
Let's write a main program to use this structure.
For this example we shall add a new node at the end of the list using the following function.
领英推荐
void addNodeToEnd(node **head, int value);
Here is the main function where we call our function to add new node.
#include <stdio.h>
#include <stdlib.h>
/**
* struct node - node for the linked list
* @value: value of int
* @next: next pointer
* Description: This is a simple node
*/
typedef struct node
{
int value;
struct node *next;
} node;
/**
* main - Linked list example
* Return: 0 success
*/
int main(void)
{
node *head = NULL;
node *current;
addNodeToEnd(&head, 45);
current = head;
/* The following code will display what is stored in the nodes */
while (current != NULL)
{
printf("Current value = %d \n", current->value);
current = current->next;
}
return (0);
}
Let's write the addNodeToEnd function.
/**
* add_new_node - function to add new node
* @head: pointer to head
* @value: integer value to be passed
* Return: pointer to new node
*/
void addNodeToEnd(node **head, int newValue)
{
node *newNode;
node *current;
newNode = malloc(sizeof(node));
if (newNode == NULL)
{
fprintf(stderr, "Memory allocation failed.\n");
exit(1);
}
newNode->value = newValue;
newNode->next = NULL;
if (*head == NULL)
*head = newNode;
else
{
current = *head;
while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
}
}
With this example above, you can add as many nodes. Each node will be linked at the end of the list. With Linked Lists you are not limited to adding nodes only at the end, you can add at any point (eg. at the beginning, middle, position n).
In my next article, I will show you how to add a node at the beginning of the Linked List.
A good understanding of pointers will make understanding Linked Lists easier. I have an article on the same here. Happy Learning.