-
Notifications
You must be signed in to change notification settings - Fork 0
/
design-linked-list.js
100 lines (87 loc) · 1.83 KB
/
design-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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var MyLinkedList = function () {
this.head = null;
this.count = 0;
};
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function (index) {
if (index < 0 || index >= this.count) {
return -1;
}
return this.getElementAt(index).val;
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function (val) {
this.addAtIndex(0, val);
};
/**
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function (val) {
this.addAtIndex(this.count, val);
};
/**
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function (index, val) {
const node = new ListNode(val);
if (index < 0) {
index = 0;
}
if (index >= 0 && index <= this.count) {
if (index === 0) {
node.next = this.head;
this.head = node;
} else {
let prev = this.getElementAt(index - 1);
node.next = prev.next;
prev.next = node;
}
this.count++;
}
};
MyLinkedList.prototype.getElementAt = function (index) {
if (index >= 0 && index < this.count) {
let curr = this.head;
for (let i = 0; i < index && curr; i++) {
curr = curr.next;
}
return curr;
}
}
/**
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function (index) {
if (index >= 0 && index < this.count) {
if (index === 0) {
this.head = this.head.next;
} else {
let prev = this.getElementAt(index - 1);
prev.next = prev.next.next;
}
this.count--;
}
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/