From 7f7e4eae3eacc15c2b7bc2db920c9e26c258cbed Mon Sep 17 00:00:00 2001 From: qiugu <33192247+qiugu@users.noreply.github.com> Date: Thu, 27 Jan 2022 03:29:51 +0800 Subject: [PATCH] feat: add linkedList insert method (#774) Co-authored-by: byj --- src/data-structures/linked-list/LinkedList.js | 34 +++++++++++++++++++ .../linked-list/__test__/LinkedList.test.js | 15 ++++++++ 2 files changed, 49 insertions(+) diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index 71c2b497..310af779 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -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} diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index f4eb83e2..cc9440f1 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -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();