Open In App

Insert a Node at Front/Beginning of a Linked List

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a linked list, the task is to insert a new node at the beginning/start/front of the linked list.

Insertion-at-the-Beginning-of-Singly-Linked-List

Example:

Input: LinkedList = 2->3->4->5, NewNode = 1
Output: LinkedList = 1->2->3->4->5

Input: LinkedList = , NewNode = 1
Output: LinkedList = 1

Approach: 

To insert a node at the start/beginning/front of a Linked List, we need to:

  • Make the first node of Linked List linked to the new node
  • Remove the head from the original first node of Linked List
  • Make the new node as the Head of the Linked List.

The below steps should be followed to insert a new node at the front of the linked list

  • Allocate a new node (say temp).
  • Put the required data into temp.
  • The ‘next’ pointer of the node should be pointed to the current head.
  • Now make the head pointer point to temp.

Below is the implementation of the approach:

C++




// C++ program to show inserting a node
// at front of given Linked List
#include <bits/stdc++.h>
using namespace std;
 
// A linked list node
class Node {
public:
    int data;
    Node* next;
};
 
// Given a reference (pointer to pointer)
// to the head of a list and an int, inserts
// a new node on the front of the list.
void insertAtFront(Node** head_ref, int new_data)
{
 
    // 1. allocate node
    Node* new_node = new Node();
 
    // 2. put in the data
    new_node->data = new_data;
 
    // 3. Make next of new node as head
    new_node->next = (*head_ref);
 
    // 4. move the head to point
    // to the new node
    (*head_ref) = new_node;
}
 
// This function prints contents of
// linked list starting from head
void printList(Node* node)
{
    while (node != NULL) {
        cout << " " << node->data;
        node = node->next;
    }
    cout << "\n";
}
 
// Driver code
int main()
{
    // Start with the empty list
    Node* head = NULL;
 
    // Insert 1 at the beginning.
    insertAtFront(&head, 1);
    insertAtFront(&head, 2);
    insertAtFront(&head, 3);
    insertAtFront(&head, 4);
    insertAtFront(&head, 5);
    insertAtFront(&head, 6);
 
    cout << "After inserting Nodes at their front: ";
  // The nodes will be : 6 5 4 3 2 1
    printList(head);
 
    return 0;
}


C




// C program to show inserting a node
// at front of given Linked List
#include <stdio.h>
#include <stdlib.h>
 
// A linked list node
struct Node {
    int data;
    struct Node* next;
};
 
// Given a reference (pointer to pointer)
// to the head of a list and an int, inserts
// a new node on the front of the list.
void insertAtFront(struct Node** head_ref, int new_data)
{
 
    // 1. allocate node
    struct Node* new_node
        = (struct Node*)malloc(sizeof(struct Node));
 
    // 2. put in the data
    new_node->data = new_data;
 
    // 3. Make next of new node as head
    new_node->next = (*head_ref);
 
    // 4. move the head to point
    // to the new node
    (*head_ref) = new_node;
}
 
// This function prints contents of
// linked list starting from head
void printList(struct Node* node)
{
    while (node != NULL) {
        printf(" %d", node->data);
        node = node->next;
    }
    printf("\n");
}
 
// Driver code
int main()
{
    // Start with the empty list
    struct Node* head = NULL;
 
    insertAtFront(&head, 1);
    insertAtFront(&head, 2);
    insertAtFront(&head, 3);
    insertAtFront(&head, 4);
    insertAtFront(&head, 5);
    insertAtFront(&head, 6);
 
    printf("After inserting nodes at their front: ");
    printList(head);
 
    return 0;
}


Java




// Java program to show inserting a node
// at front of given Linked List
import java.io.*;
 
// A linked list node
class Node {
    int data;
    Node next;
}
 
// Class to insert element in LL
class LinkedList {
    Node head; // head of list
 
    // Given a reference (pointer to pointer)
    // to the head of a list and an int, inserts
    // a new node on the front of the list.
    void insertAtFront(int new_data)
    {
        // 1. allocate node
        Node new_node = new Node();
 
        // 2. put in the data
        new_node.data = new_data;
 
        // 3. Make next of new node as head
        new_node.next = head;
 
        // 4. move the head to point
        // to the new node
        head = new_node;
    }
 
    // This function prints contents of
    // linked list starting from head
    void printList()
    {
        Node node = head;
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Start with the empty list
        LinkedList list = new LinkedList();
 
        list.insertAtFront(6);
        list.insertAtFront(5);
        list.insertAtFront(4);
        list.insertAtFront(3);
        list.insertAtFront(2);
        list.insertAtFront(1);
 
        System.out.print(
            "After inserting nodes at their front: ");
        list.printList();
    }
}


Python3




# Python3 program to show inserting a node
# at front of given Linked List
 
# A linked list node
 
 
class Node:
    def __init__(self):
        self.data = None
        self.next = None
 
# Given a reference (pointer to pointer)
# to the head of a list and an int, inserts
# a new node on the front of the list.
 
 
def insertAtFront(head_ref, new_data):
 
    # 1. allocate node
    new_node = Node()
 
    # 2. put in the data
    new_node.data = new_data
 
    # 3. Make next of new node as head
    new_node.next = head_ref
 
    # 4. move the head to point
    # to the new node
    head_ref = new_node
 
    return head_ref
 
 
# This function prints contents of
# linked list starting from head
 
 
def printList(node):
    while (node != None):
        print(node.data, end=" ")
        node = node.next
    print("\n")
 
 
# Driver code
if __name__ == '__main__':
    # Start with the empty list
    head = None
 
    head = insertAtFront(head, 6)
    head = insertAtFront(head, 5)
    head = insertAtFront(head, 4)
    head = insertAtFront(head, 3)
    head = insertAtFront(head, 2)
    head = insertAtFront(head, 1)
 
    print("After inserting nodes at thier front: ", end="")
    printList(head)


C#




// C# program to show inserting a node
// at front of given Linked List
using System;
 
class GFG {
    public Node head; // head of list
 
    /* Linked list Node*/
    public class Node {
        public int data;
        public Node next;
        public Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    /* Inserts a new Node at front of the list. */
    public void insertAtFront(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                Put in the data*/
        Node new_node = new Node(new_data);
 
        /* 3. Make next of new Node as head */
        new_node.next = head;
 
        /* 4. Move the head to point to new Node */
        head = new_node;
    }
 
    /* This function prints contents of linked list
    starting from the given node */
    public void printList()
    {
        Node tnode = head;
        while (tnode != null) {
            Console.Write(tnode.data + " ");
            tnode = tnode.next;
        }
        Console.WriteLine();
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        /* Start with the empty list */
        GFG llist = new GFG();
 
        llist.insertAtFront(6);
        llist.insertAtFront(5);
        llist.insertAtFront(4);
        llist.insertAtFront(3);
        llist.insertAtFront(2);
        llist.insertAtFront(1);
 
        Console.Write("After inserting nodes at their front: ");
        llist.printList();
    }
}


Javascript




// A linked list node
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
// Given a reference (pointer to pointer)
// to the head of a list and an int, inserts
// a new node on the front of the list.
function insertAtFront(head_ref, new_data) {
    // 1. Create a new node
    const new_node = new Node(new_data);
 
    // 2. Make the new node point to the current head
    new_node.next = head_ref[0];
 
    // 3. Update the head to the new node
    head_ref[0] = new_node;
}
 
// This function prints contents of
// linked list starting from head
function printList(node) {
    let current = node;
    while (current !== null) {
        console.log(" " + current.data);
        current = current.next;
    }
    console.log("\n");
}
 
// Driver code
function main() {
    // Start with an empty list
    const head = [null]; // Use an array to simulate a pointer to pointer
 
    // Insert elements at the beginning
    insertAtFront(head, 1);
    insertAtFront(head, 2);
    insertAtFront(head, 3);
    insertAtFront(head, 4);
    insertAtFront(head, 5);
    insertAtFront(head, 6);
 
    console.log("After inserting Nodes at their front:");
    // The nodes will be: 6 5 4 3 2 1
    printList(head[0]);
}
 
main();


Output

Created Linked list is:  2 3 4 5 6
After inserting 1 at front:  1 2 3 4 5 6



Explanation: In the above code we have inserted nodes before them and each node is inserted before the already inserted nodes.

Time Complexity: O(1)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads