Insert Node At The Beginning of Linked List

In this post, you will learn how to insert new node at the beginning of the Linked List, Code for the above task given below:

Insert Node At The Beginning of Linked List

How To Insert Node At The Beginning of Linked List?

struct node{
    int data;
    struct node *next;
};
struct node *head=NULL;

void insertElementAtBeginning(int val){
struct node *New = malloc(sizeof(struct node));
New->data = val;
New->next = head;

head = New;
}

In this program, we are doing following things:

  1. Creating a structure for node, which contains a value and pointer. 
  2. After this we are creating a node head which is empty.
  3. Now allocating the memory in heap for the node New.
  4. Inserting the data in it and connecting to the next node that is head.
  5. After this we are making the New node head.

So this is how the function is working.


#include<stdio.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node *next;
};

struct node *head = NULL;

void insertElementAtBeginning(int val){
struct node *New = malloc(sizeof(struct node));
New->data = val;
New->next = head;
head = New;
}

void print(){
    struct node *temp = head;
    while(temp != NULL)
    {
         printf("%d ", temp->data);
         temp = temp->next;
    }
}

int main(){
     insertElementAtBeginning(1);
     insertElementAtBeginning(2);
     insertElementAtBeginning(3);
     print();
     return 0;
}
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment