-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked-list.js
77 lines (60 loc) · 1.51 KB
/
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// list node ---> elements/items
const { ListNode } = require("./list-node");
// { value: 4, next: null }
// initialize --> head, size
// Insert/Add at particular index, begin, end
// Delete at a particular index, begin, end
// Get the value of node at a particular index
function LinkedList() {
this.head = new ListNode(0);
this.size = 0;
}
LinkedList.prototype.addAtIndex = function(index, value) {
if (index < 0 || index > this.size) {
return null;
}
let pre = this.head;
let i = 0;
while (i < index) {
pre = pre.next;
i++;
}
const currRef = pre.next;
const newNode = new ListNode(value);
pre.next = newNode;
newNode.next = currRef;
this.size += 1;
}
LinkedList.prototype.addAtStart = function(value) {
return this.addAtIndex(0, value);
}
LinkedList.prototype.deleteAtIndex = function(index) {
if (index < 0 || index >= this.size) {
return null;
}
let pre = this.head;
let i = 0;
while (i < index) {
pre = pre.next;
i++;
}
const nodeToDelete = pre.next;
pre.next = pre.next.next;
this.size -= 1;
return nodeToDelete;
}
LinkedList.prototype.getNodeAtIndex = function(index) {
if (index < 0 || index > this.size) {
return null;
}
let pre = this.head;
let i = 0;
while (i <= index) {
pre = pre.next;
i++;
}
return pre;
}
exports.LinkedList = LinkedList
/// sentinal ---> 1 ---> 2 -----> 3
/// sentinal ---> 1 --> 5 --> 2 -----> 3