-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array-to-Linked-List.js
56 lines (38 loc) · 1.14 KB
/
Array-to-Linked-List.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Defining Node class
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Defining Singly Linked List class
class SinglyLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
// =====================Methods=======================
arrayToLinkedList(arr) {
if (arr.length === 0) {
const result = "Provided Array is a Empty Array";
return result;
}
this.head = new Node(arr[0]);
let current = this.head;
for (let i = 1; i < arr.length; i++) {
current.next = new Node(arr[i]);
current = current.next;
}
// Update the Tail node with the new tail
this.tail = current;
// Return the Linked List
return this;
}
}
// Create a new singly linked list
const myList = new SinglyLinkedList();
// Test the arrayToLinkedList method
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [];
console.log(myList.arrayToLinkedList(arr1)); // Output: Node { data: 1, next: Node { data: 2, next: Node { data: 3, next: Node { data: 4, next: Node { data: 5, next: null } } } } }
console.log(myList.arrayToLinkedList(arr2)); // Output: Empty Array