Write a C program to insert a node at the beginning of linked list. In this tutorial, we create a linked list and insert a new node at the beginning/head of linked list.
A Linked list is a linear data structure which consists a group of nodes and each node points to next node by means of a pointer. In Linked list, a node consists of two parts, a data and a pointer to next node.
Algorithm to insert node at the beginning of a linked list
1. Create a new node dynamically (by allocating a memory).
2. Insert a data and point the new node to the next node.
3. Put a reference of head node to the new node. So that head node points to a new node.
C Program to Insert a Node at the Beginning of Linked List
We have discussed, what is linked list? and algorithm to insert a node at the beginning of linked list. Let’s write a code to insert a node at the head of a linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#include <stdio.h> /* Node structure */ struct node{ int data; struct node* next; }; struct node* head; //Insert node at the head of linked list void insert_node(int data){ /* Allocate memory to newly created node. */ struct node* newnode=(struct node*)malloc(sizeof(struct node*)); //data newnode->data = data; //Newnode points to head newnode->next = head; head = newnode; } void print(){ struct node* p; p = head; //Traverse and print while(p != NULL){ printf("%d\n",p->data); p=p->next; } } int main() { /* Initially head is NULL, it doesn't point to any node. */ head = NULL; /* insert_node function create new node dynamically. */ insert_node(2); insert_node(4); insert_node(6); insert_node(8); /* Print value. */ print(); return 0; } |
Linked list is also a very important topic in terms of interviews. Most asked linked list interview questions.
Count number of nodes in a linked list
Program to find middle element of a linked list
Reverse a Linked List using Recursion