Simple Linked List Creation

This post is about one of the most interesting and challenging data structure “linked list” Let me not use any technical terms right away to explain stuffs

Consider a train which consists ‘n’ number of compartments/carriages chained with each other in such a way that they almost form a list-like structure. The engine/first compartment of your train which we ll refer here as the head of the train, is linked to the second compartment, which is in turn linked to another and so on. The last compartment consists of a guard / a big red cross mark that denotes the end of the train and no other compartments are to be found after that.

Now consider your linked list to be one such train , where all your nodes are linked to each other on a one-to-one basis and the last node is linked to NULL . Also note that the first node of your linked is called the head of the linked list.

Before we move further, let ‘s first try answering the question: What is a node?

A node is a record consisting of one or more fields that are links to other nodes and a data field i.e., Data + link to another node is together known as a node.i.e.,(one/more) Data + Address of/Link to the next node.

How do we code a node?

struct node{
int data; // data part of the node
struct node * next ; // pointer to the next node in the linked list

A Simple C program to create a linked list


struct node
int data;
struct node *next;
void printList(struct node* run)
while(run!=NULL) //traverse the linked list from head to end
printf(“%d->”,run->data); // print the data in the linked list
run=run->next; //goto next node in the linked list
int main()
struct node* first = (struct node*)malloc(sizeof(struct node*));//dynamically memory allocation to the node
struct node* second = (struct node*)malloc(sizeof(struct node));
struct node* third = (struct node*)malloc(sizeof(struct node));
first->data = 1; //assign data in first node
first->next = second; // Link head node with the second node
second->data = 2; //assign data to second node
second->next = third;
third->data = 3; //assign data to third node
third->next = NULL;
printList(first);//passing the head node of the linked list
return 0;

Thus you have created a linked list successfully . Will keep updating more on related data structures.
HAve any doubts ? Do leave a message below !!

Latest posts by abirami vijayakumar (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *