Road To Code

Road To Code

Insertion at the beginning of the Singly linked lists

Yash Naravade's photo
Yash Naravade

Published on Oct 7, 2021

2 min read

Subscribe to our newsletter and never miss any upcoming articles

Listen to this article

By now you must be well versed with the concept of Linked list. We learned how to make a linked list and traverse it. In this article we will see how you can insert a node at the beginning of a linked list.

Approach:

  1. Declare a head pointer and make it as NULL.

  2. Create a new node with data.

  3. Make the new node points to the head node.

  4. Finally, make the new node as the head node.

Example:

Suppose that the linked list has elements, 10->15->20->NULL.
Now, if we insert 5 at beginning of a linked list, it will look like,
5->15->20->NULL.

Code:

#include<bits/stdc++.h>
using namespace std;

class Node{
    public:
    int data;
    Node *next;
    Node()
    {
        this->next = NULL;
    }
};

void traverseLinkedList(Node *node)
{
    while(node!=NULL)
    {
        cout<<node->data<<", ";
        node = node->next;
    }
}

void insertAtBeginning(int data, Node * &head)
{
    Node *newNode = new Node();
    newNode->data = data;

    newNode->next = head;
    head= newNode;
}

int main()
{
    Node *head = new Node();
    head->data = 10;

    Node *first = new Node();
    first->data = 15;

    Node *last = new Node();
    last->data = 20;

    head->next = first;
    first->next = last;

    cout<<"Before Insertion: ";
    traverseLinkedList(head);

    insertAtBeginning(5, head);

    cout<<"\nAfter Insertion: ";
    traverseLinkedList(head);

    return 0;
}

Output:

Before Insertion: 10, 15, 20, 
After Insertion: 5, 10, 15, 20,

This is how to insert a node at beginning of a singly linked list.

 
Share this