Skip to content

Commit 7f7e4ea

Browse files
qiugubyj
and
byj
authored
feat: add linkedList insert method (trekhleb#774)
Co-authored-by: byj <[email protected]>
1 parent 5b64117 commit 7f7e4ea

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/data-structures/linked-list/LinkedList.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,40 @@ export default class LinkedList {
5454
return this;
5555
}
5656

57+
/**
58+
* @param {*} value
59+
* @param {*} index
60+
* @return {LinkedList}
61+
*/
62+
insert(value, index) {
63+
index = index < 0 ? 0 : index;
64+
if (index === 0) {
65+
this.prepend(value);
66+
} else {
67+
let count = 1;
68+
let currentNode = this.head;
69+
const newNode = new LinkedListNode(value);
70+
while (currentNode) {
71+
if (count === index) break;
72+
currentNode = currentNode.next;
73+
count++;
74+
}
75+
if (currentNode) {
76+
newNode.next = currentNode.next;
77+
currentNode.next = newNode;
78+
} else {
79+
if (this.tail) {
80+
this.tail.next = newNode;
81+
this.tail = newNode;
82+
} else {
83+
this.head = newNode;
84+
this.tail = newNode;
85+
}
86+
}
87+
}
88+
return this;
89+
}
90+
5791
/**
5892
* @param {*} value
5993
* @return {LinkedListNode}

src/data-structures/linked-list/__test__/LinkedList.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,21 @@ describe('LinkedList', () => {
3232
expect(linkedList.toString()).toBe('3,2,1');
3333
});
3434

35+
it('should insert node to linked list', () => {
36+
const linkedList = new LinkedList();
37+
38+
linkedList.insert(4, 3);
39+
expect(linkedList.head.toString()).toBe('4');
40+
expect(linkedList.tail.toString()).toBe('4');
41+
42+
linkedList.insert(3, 2);
43+
linkedList.insert(2, 1);
44+
linkedList.insert(1, -7);
45+
linkedList.insert(10, 9);
46+
47+
expect(linkedList.toString()).toBe('1,4,2,3,10');
48+
})
49+
3550
it('should delete node by value from linked list', () => {
3651
const linkedList = new LinkedList();
3752

0 commit comments

Comments
 (0)