Skip to content

Commit 5c08f1d

Browse files
committed
feat: Solve insert node in linked list
- Hackerrank
1 parent 8e1b174 commit 5c08f1d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

insert-node-linked-list.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Hackerrank
3+
* You’re given the pointer to the head node of a linked list, an integer to
4+
* add to the list and the position at which the integer must be inserted.
5+
* Create a new node with the given integer, insert this node at the desired
6+
* position and return the head node.
7+
*
8+
* Constraints:
9+
* 1. 1 <= n <= 1000
10+
* 2. 1 <= SingleLinkedListNode[i].data <= 1000
11+
* 3. 0 <= position <= n
12+
*
13+
* This solution got 5 points
14+
* Problem link: http://hr.gs/vnu
15+
*/
16+
17+
/*
18+
* For your reference:
19+
*
20+
* SinglyLinkedListNode {
21+
* int data;
22+
* SinglyLinkedListNode next;
23+
* }
24+
*
25+
*/
26+
27+
/**
28+
* @param {SinglyLinkedListNode} head The root of the linked list
29+
* @param {number} data The new data to be added to the linked list
30+
* @param {number} position The index position in which the new data will be placed on
31+
* @return {SinglyLinkedListNode} The root of the linked list
32+
*/
33+
function insertNodeAtPosition(head, data, position) {
34+
// Edge case
35+
if (!head) {
36+
return { data };
37+
}
38+
let node = head;
39+
let found = false;
40+
let i = 0;
41+
while (node.next && !found) {
42+
if (i + 1 === position && node.next) {
43+
const prev = node.next;
44+
node.next = { data, next: prev };
45+
found = true;
46+
}
47+
node = node.next;
48+
i++;
49+
}
50+
return head;
51+
}

0 commit comments

Comments
 (0)