-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.js
106 lines (92 loc) · 1.99 KB
/
LinkedList.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
insertAtHead(data) {
const newNode = new ListNode(data);
// newNode.next = this.head;
// newNode.prev = this.head;
this.head = newNode;
this.length++;
}
unshift(data) {
const newNode = new ListNode(data);
if(!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
newNode.prev = null;
this.head = newNode;
}
this.length++;
}
enqueue(data) {
const newNode = new ListNode(data);
if(this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
}
dequeue() {
let current = this.head;
if(current) {
this.head = current.next;
}
this.length--;
}
pop() {
if(!this.head) return null;
if(this.length === 1) {
this.head = null;
this.tail = null;
} else {
this.tail = this.tail.prev;
this.tail.next = null;
}
this.length--;
}
getByIndex(index) {
if (index < 0 || index >= this.length) return null;
let current = this.head;
for(let i = 0; i < index; i++) {
current = current.next;
}
return current;
}
insertAtIndex(data, index) {
if (index === 0) return this.insertAtHead(data);
const prev = this.getByIndex(index - 1);
if(prev == null) return null;
prev.next = new ListNode(data, prev.next);
this.length ++;
return prev;
}
getHead() {
return this.head;
}
print() {
let output = '';
let current = this.head;
while(current) {
output = `${output}${current.value}-->`;
console.log(current)
current = current.next;
}
console.log(`${output}null`);
}
}
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
module.exports = LinkedList;