Skip to content

Instantly share code, notes, and snippets.

@rahul4coding
Last active October 21, 2022 05:50
Show Gist options
  • Save rahul4coding/830ac4607e938b5e2813482806b38de2 to your computer and use it in GitHub Desktop.
Save rahul4coding/830ac4607e938b5e2813482806b38de2 to your computer and use it in GitHub Desktop.
Insert node at specified position in a Linked List | JS
function insertNodeAtPosition(head, data, position) {
var trackedNode = head;
var newNode = new SinglyLinkedListNode(data);
if(head==null){
head = newNode
return head;
}
if(position==0){
newNode.next = head;
return newNode;
}
var currentPostion =0;
while(currentPostion<position-1 && head.next!==null){
head = head.next
currentPostion++
}
//now we are at position-1
var nodeAtPosition = head.next
head.next = newNode
head = head.next
newNode.next = nodeAtPosition
return trackedNode;
}
@Preetiraj3697
Copy link

Insert at a specific position -60:40:14
Description

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node.

A position of 0 indicates head, a position of 1 indicates one node away from the head, and so on. The head pointer given may be null meaning that the initial list is empty.

Complete the functioninsertNodeAtPositionin 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

Sample Input 1

3
16
13
7
1
2
Sample Output 1

16 13 1 7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment