feat: add linkedList insert method (#774)

Co-authored-by: byj <youjia.bi@weimob.com>
This commit is contained in:
qiugu 2022-01-27 03:29:51 +08:00 committed by GitHub
parent 5b64117a2c
commit 7f7e4eae3e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 0 deletions

View File

@ -54,6 +54,40 @@ export default class LinkedList {
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
* @return {LinkedListNode}

View File

@ -32,6 +32,21 @@ describe('LinkedList', () => {
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', () => {
const linkedList = new LinkedList();