/**
* @author https://codeforwin.org
* @date 20 July 2025, 23:05
* @version 1.0
* @description C program to create and traverse a Linked List
*/
#include <stdio.h>
#include <stdlib.h>
/* Structure of a node */
typedef struct node
{
int data; // Stores integer value, can be char, struct etc.
struct node* next; // Pointer to next node
} node;
// Functions to create, traverse and display list
node* createNode(int data);
node* createList(int nodeCount);
void traverseList(node* head);
void freeList(node* head);
int main()
{
int totalNode;
node *head;
printf("Enter the total number of nodes: ");
scanf("%d", &totalNode);
head = createList(totalNode);
printf("\nData in the list \n");
traverseList(head);
freeList(head);
return 0;
}
/**
* Creates a new node with the given data and returns the pointer to the node.
*/
node* createNode(int data)
{
// Allocate memory for new node
node* newNode = (node*) malloc(sizeof(node));
if (newNode == NULL)
{
// Memory allocation failed, exit program
printf("Memory allocation failed!");
exit(1);
}
// Initialise node data and pointer
newNode->data = data;
newNode->next = NULL;
return newNode;
}
/**
* Create a list of nodes. Returns the pointer to head node.
*/
node* createList(int nodeCount)
{
node *head = NULL, *newNode = NULL, *prevNode = NULL;
int data, counter;
// No new node to create
if (nodeCount <= 0)
{
printf("No nodes to create");
return head;
}
for (counter = 1; counter <= nodeCount; counter++)
{
// Read data in the node from user
printf("Input data at node %d: ", counter);
scanf("%d", &data);
// Create a new node
newNode = createNode(data);
if (prevNode != NULL)
{
// Link previous node with newNode
prevNode->next = newNode;
}
// For next iteration make current node as previous node
prevNode = newNode;
// Ensure head points to the first node in the list
if (counter == 1)
{
head = newNode;
}
}
return head;
}
/**
* Traverses through entire linked list and prints data to console.
*/
void traverseList(node* head)
{
node* current = head; // Start from head
while (current != NULL)
{
printf("%d -> ", current->data); // Print data of current node
current = current->next; // Move to next node
}
printf("\n");
}
/**
* Traverses from head till NULL, deletes all the allocated bytes.
*/
void freeList(node* head)
{
printf("Clearing memory!");
node* current;
while (head != NULL)
{
current = head;
// Move head to next node
head = head->next;
// Clear the current node
free(current);
}
}