Insert Node at the Beginning of the Linked List

Insert Node at the Beginning of the Linked List” is the very basic problem of linked list for beginners. Here, the new node of the linked list is added before the head of the linked list and the new node will then become new head of the linked list. 

Example:

If the current linked list is 
{2->3->4}
Then after inserting node with value 1, the newly linked list will become 
{1->2->3->4}

The steps required to insert the new node at the beginning of the singly linked list are as follows:

  1. Create a new node with the desired value in data part and NULL value in pointer part.
  2. Check whether linked list is empty or not.
  3. If linked list is empty, then the new node will become the head of the linked list.
  4. Else if linked is not empty, then the pointer part of the new node will point to the head of the linked list and the new node will become the new head of the linked list.

C++ Program to Insert Node at the beginning of the linked list is as follows:

/* C++ Program to insert node at the beginning of the linked list */  
#include<bits/stdc++.h>
using namespace std;
/* Node Structure */  
struct node  
{  
    int data;  
    struct node *next;  
};  
/* Creating New Node */  
struct node *create(struct node **new_node, int ele)  
{  
    (*new_node) = (struct node*)malloc(sizeof(struct node));  
    (*new_node)->data = ele;  
    (*new_node)->next = NULL;  
    return (*new_node);  
}  
/* Inserting Node at beginning of the linked list */  
void insert_beg(struct node **head, int ele)  
{  
    // Creating a new node.  
    struct node *new_node;  
    new_node = (struct node*)malloc(sizeof(struct node));  
    new_node->data = ele;  
    new_node->next = NULL;  
      
    // check whether the linked list is empty or not  
    if(*head == NULL)     // if empty  
    {  
        *head = new_node;  
        return;  
    }  
    // if not empty  
    new_node -> next = (*head);  
    (*head) = new_node;  
}  
/* Printing the linked list */  
void print(struct node *head)  
{  
    struct node *p = head;  
    while(p!=NULL)  
    {  
        cout<<p->data<<" ";  
        p=p->next;  
    }  
}  
int main()  
{  
    struct node *head;  
    head = NULL;  
    cout<<"Inserting 3 new nodes at the beginning\n";
    insert_beg(&head,3);  
    insert_beg(&head,2);  
    insert_beg(&head,1);  
    cout<<"\nThe Nodes of the linked list are:\n";  
    print(head);  
}  
OUTPUT:
Inserting 3 new nodes at the beginning
The Nodes of the linked list are:
1 2 3

You may also like...

Leave a Reply

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