Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Preetiraj3697/52cfbbf033ce32a7e4cbbe4b12e0ef0e to your computer and use it in GitHub Desktop.
Save Preetiraj3697/52cfbbf033ce32a7e4cbbe4b12e0ef0e 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
Author

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