-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesignLL.js
68 lines (61 loc) · 1.59 KB
/
designLL.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
class Node {
constructor(val = null, prev = null, next = null) {
this.val = val;
this.prev = prev;
this.next = next;
}
}
class MyLinkedList {
constructor() {
this.head = new Node();
this.tail = new Node();
this.length = 0;
this.head.next = this.tail;
this.tail.prev = this.head;
}
get(idx) {
if(idx < 0 || idx >= this.length) return -1;
let curr = this.head.next;
while(idx--) curr=curr.next;
return curr.val
}
addAtHead(val) {
let prev = this.head;
let next = this.head.next;
let node = new Node(val, prev, next);
prev.next = node;
next.prev = node;
this.length++;
}
addAtTail(val) {
let prev = this.tail.prev;
let next = this.tail;
let node = new Node(val, prev, next);
prev.next = node;
next.prev = node;
this.length++;
}
addAtIndex(idx, val) {
if(idx<0|| idx > this.length) return null;
if(idx === this.length) {
this.addAtTail(val);
return;
}
let prev = this.head;
while(idx--) prev = prev.next;
let next = prev.next;
let node = new Node(val, prev, next);
prev.next = node;
next.prev = node;
this.length++;
}
deleteAtIndex(idx) {
if(idx < 0 || idx >= this.length) return null;
let prev = this.head;
while(idx--) prev = prev.next;
let next = prev.next.next;
prev.next = next;
next.prev = prev;
this.length--;
}
}