Insert a Node at the Head of a Linked List. HackerRank Exercise

This exercise is a part of my Linked List topic.

You’re given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer, insert this node at the head of the linked list and return the new head node. The head pointer given may be null meaning that the initial list is empty.

Input Format

You have to complete the SinglyLinkedListNode Insert(SinglyLinkedListNode head, int data) method which takes two arguments — the head of the linked list and the integer to insert. You should NOT read any input from stdin/console.

The input is handled by code in the editor and is as follows:

The first line contains an n integer, denoting the number of elements to be inserted at the head of the list.
The next n lines contain an integer each, denoting the element to be inserted.


This is a classic Linked List Node realization below

Completed exercise bellow:

Here imported Linked List Node class SinglyLinkedListNode like in previous posts about Linked List.

Here we need to create a new Node item from input data. And set to his next value input Linked List. Our data should be a new head node, and the input Linked list Node (which actually just a first element of Linked List with reference to other nodes) need to be the second element in the new output list


At first, we created the Linked List with 3 nodes (1, 2, 3) (node1 is the head node of input Linked List). After calling the loop through the new result variable we will get the next result (33, 1, 2, 3). So the Node with 33 was successfully added to input Linked List.

Github project

My social media

LinkedIn Twitter Original Blog Github HackerRank



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store