-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution-singly-head-tail.ts
99 lines (77 loc) · 2.12 KB
/
solution-singly-head-tail.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
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
import { MyLinkedListClass, LinkNode } from './types';
/*
* @lc app=leetcode id=707 lang=javascript
*
* [707] Design Linked List
*/
// @lc code=start
class MyLinkedList implements MyLinkedListClass {
// * ['116 ms', '82.77 %', '42.3 MB', '100 %']
// * singly, head and tail, but not so good
private head: LinkNode | null = null;
private tail: LinkNode | null = null;
private length = 0;
constructor() {}
private addfromEmpty(val: number): void {
this.head = this.tail = { val, next: null };
}
addAtHead(val: number) {
if (this.length === 0) {
this.addfromEmpty(val);
} else {
this.head = { val, next: this.head };
}
this.length++;
}
addAtTail(val: number) {
if (this.length === 0) {
this.addfromEmpty(val);
} else {
this.tail = this.tail!.next = { val, next: null };
}
this.length++;
}
get(index: number) {
if (index < 0 || this.length <= index) return -1;
let cur = this.head!;
for (let i = 0; i < index; i++) cur = cur.next!;
return cur.val;
}
addAtIndex(index: number, val: number) {
if (index < 0 || this.length < index) return;
if (index === 0) return this.addAtHead(val);
if (index === this.length) return this.addAtTail(val);
let cur = this.head!;
for (let i = 1; i < index; i++) cur = cur.next!;
cur.next = { val, next: cur.next };
this.length++;
}
deleteAtIndex(index: number) {
if (index < 0 || this.length <= index) return;
if (this.length === 1) {
this.head = this.tail = null;
this.length = 0;
return;
}
if (index === 0) {
this.head = this.head!.next;
} else {
let cur = this.head!;
for (let i = 1; i < index; i++) cur = cur.next!;
cur.next = cur.next!.next;
if (index === this.length - 1) this.tail = cur;
}
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 };