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

Class LinkedList

Data-Structures/Linked-List/SinglyLinkedList.js:18–303  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

16}
17
18class LinkedList {
19 constructor(listOfValues) {
20 this.headNode = null
21 this.tailNode = null
22 this.length = 0
23
24 if (listOfValues instanceof Array) {
25 for (const value of listOfValues) {
26 this.addLast(value)
27 }
28 }
29 }
30
31 // initiates the currentNode and currentIndex and return as an object
32 initiateNodeAndIndex() {
33 return { currentNode: this.headNode, currentIndex: 0 }
34 }
35
36 // Returns length
37 size() {
38 return this.length
39 }
40
41 // Returns the head
42 head() {
43 return this.headNode?.data ?? null
44 }
45
46 // Returns the tail
47 tail() {
48 return this.tailNode?.data ?? null
49 }
50
51 // Return if the list is empty
52 isEmpty() {
53 return this.length === 0
54 }
55
56 // add a node at last it to linklist
57 addLast(element) {
58 // Check if its the first element
59 if (this.headNode === null) {
60 return this.addFirst(element)
61 }
62 const node = new Node(element)
63 // Adding node at the end of the list and increase the length
64 this.tailNode.next = node
65 this.tailNode = node
66 this.length++
67 return this.size()
68 }
69
70 // add a node at first it to linklist
71 addFirst(element) {
72 const node = new Node(element)
73 // Check if its the first element
74 if (this.headNode === null) {
75 this.tailNode = node

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected