-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution-singly-dummy.ts
73 lines (55 loc) · 1.54 KB
/
solution-singly-dummy.ts
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
import { MyLinkedListClass, LinkNode } from './types';
/*
* @lc app=leetcode id=707 lang=javascript
*
* [707] Design Linked List
*/
// @lc code=start
class MyLinkedList implements MyLinkedListClass {
// * ['112 ms', '91.18 %', '42.2 MB', '100 %']
// * singly, simple code but slow
private dummy: LinkNode = { val: 0, next: null };
private length = 0;
constructor() {}
get(index: number) {
if (index < 0 || this.length <= index) return -1;
let cur = this.dummy.next!;
for (let i = 0; i < index; i++) cur = cur.next!;
return cur.val;
}
addAtHead(val: number) {
this.dummy.next = { val, next: this.dummy.next };
this.length++;
}
addAtTail(val: number) {
let cur = this.dummy;
while (cur.next) cur = cur.next;
cur.next = { val, next: null };
this.length++;
}
addAtIndex(index: number, val: number) {
if (index < 0 || this.length < index) return;
let cur = this.dummy;
for (let i = 0; i < index; i++) cur = cur.next!;
cur.next = { val, next: cur.next };
this.length++;
}
deleteAtIndex(index: number) {
if (index < 0 || this.length <= index) return;
let cur = this.dummy;
for (let i = 0; i < index; i++) cur = cur.next!;
cur.next = cur.next!.next;
this.length--;
}
}
/**
* 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)
*/
// @lc code=end
export { MyLinkedList };