Insert the node at a position

Function Description Complete the function insertNodeAtPosition in the editor below. It must return a reference to the head node of your finished list.

insertNodeAtPosition has the following parameters:

  • head: a SinglyLinkedListNode pointer to the head of the list
  • data: an integer value to insert as data in your new node
  • position: an integer position to insert the new node, zero-based indexing

Input Format

The first line contains an integer, the number of elements in the linked list.
Each of the next  lines contains an integer SinglyLinkedListNode[i].data.
The next line contains an integer denoting the data of the node that is to be inserted.
The last line contains an integer.

Constraints

  • 1. n is between 1 to 1000
  • 2. positions between 0 to n 

Output Format

Return a reference to the list head. Locked code prints the list for you.

This is a HackerRank problem at :

https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem

C++ solution: 

Time Complexity: O(n)

Click here to refresh more on Algorithms.