MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / DoubleLinkedList

Class DoubleLinkedList

Data-Structures/Linked-List/DoublyLinkedList.js:9–224  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

7}
8
9class DoubleLinkedList {
10 constructor() {
11 this.length = 0
12 this.head = null
13 this.tail = null
14 }
15
16 // Add new element
17 append(element) {
18 const node = new Node(element)
19
20 if (!this.head) {
21 this.head = node
22 this.tail = node
23 } else {
24 node.prev = this.tail
25 this.tail.next = node
26 this.tail = node
27 }
28
29 this.length++
30 }
31
32 // Add element
33 insert(position, element) {
34 // Check of out-of-bound values
35 if (position >= 0 && position <= this.length) {
36 const node = new Node(element)
37 let current = this.head
38 let previous = 0
39 let index = 0
40
41 if (position === 0) {
42 if (!this.head) {
43 this.head = node
44 this.tail = node
45 } else {
46 node.next = current
47 current.prev = node
48 this.head = node
49 }
50 } else if (position === this.length) {
51 current = this.tail
52 current.next = node
53 node.prev = current
54 this.tail = node
55 } else {
56 while (index++ < position) {
57 previous = current
58 current = current.next
59 }
60
61 node.next = current
62 previous.next = node
63
64 // New
65 current.prev = node
66 node.prev = previous

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected