mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-27 15:41:16 +08:00
feat: add linkedList insert method (#774)
Co-authored-by: byj <youjia.bi@weimob.com>
This commit is contained in:
parent
5b64117a2c
commit
7f7e4eae3e
@ -54,6 +54,40 @@ export default class LinkedList {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {*} value
|
||||||
|
* @param {*} index
|
||||||
|
* @return {LinkedList}
|
||||||
|
*/
|
||||||
|
insert(value, index) {
|
||||||
|
index = index < 0 ? 0 : index;
|
||||||
|
if (index === 0) {
|
||||||
|
this.prepend(value);
|
||||||
|
} else {
|
||||||
|
let count = 1;
|
||||||
|
let currentNode = this.head;
|
||||||
|
const newNode = new LinkedListNode(value);
|
||||||
|
while (currentNode) {
|
||||||
|
if (count === index) break;
|
||||||
|
currentNode = currentNode.next;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
if (currentNode) {
|
||||||
|
newNode.next = currentNode.next;
|
||||||
|
currentNode.next = newNode;
|
||||||
|
} else {
|
||||||
|
if (this.tail) {
|
||||||
|
this.tail.next = newNode;
|
||||||
|
this.tail = newNode;
|
||||||
|
} else {
|
||||||
|
this.head = newNode;
|
||||||
|
this.tail = newNode;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {*} value
|
* @param {*} value
|
||||||
* @return {LinkedListNode}
|
* @return {LinkedListNode}
|
||||||
|
@ -32,6 +32,21 @@ describe('LinkedList', () => {
|
|||||||
expect(linkedList.toString()).toBe('3,2,1');
|
expect(linkedList.toString()).toBe('3,2,1');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should insert node to linked list', () => {
|
||||||
|
const linkedList = new LinkedList();
|
||||||
|
|
||||||
|
linkedList.insert(4, 3);
|
||||||
|
expect(linkedList.head.toString()).toBe('4');
|
||||||
|
expect(linkedList.tail.toString()).toBe('4');
|
||||||
|
|
||||||
|
linkedList.insert(3, 2);
|
||||||
|
linkedList.insert(2, 1);
|
||||||
|
linkedList.insert(1, -7);
|
||||||
|
linkedList.insert(10, 9);
|
||||||
|
|
||||||
|
expect(linkedList.toString()).toBe('1,4,2,3,10');
|
||||||
|
})
|
||||||
|
|
||||||
it('should delete node by value from linked list', () => {
|
it('should delete node by value from linked list', () => {
|
||||||
const linkedList = new LinkedList();
|
const linkedList = new LinkedList();
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user