-
-
Save Preetiraj3697/52cfbbf033ce32a7e4cbbe4b12e0ef0e to your computer and use it in GitHub Desktop.
Insert node at specified position in a Linked List | JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Input 1
3
16
13
7
1
2
Sample Output 1
16 13 1 7