-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListDesign.ts
110 lines (93 loc) · 2.57 KB
/
LinkedListDesign.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
100
101
102
103
104
105
106
107
108
109
110
class Node {
val: number;
next: Node | null;
prev: Node | null;
constructor(val: number, next: Node | null = null, prev: Node | null = null) {
this.val = val;
this.next = next;
this.prev = prev;
}
}
class MyLinkedList {
head: Node | null;
tail: Node | null;
length: number;
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
get(index: number): number {
if (index < 0 || index >= this.length) return -1;
let current = this.head;
for (let i = 0; i < index; i++) {
current = current!.next;
}
return current!.val;
}
addAtHead(val: number): void {
const newNode = new Node(val, this.head, null);
if (this.head) {
this.head.prev = newNode;
} else {
this.tail = newNode;
}
this.head = newNode;
this.length++;
}
addAtTail(val: number): void {
const newNode = new Node(val, null, this.tail);
if (this.tail) {
this.tail.next = newNode;
} else {
this.head = newNode;
}
this.tail = newNode;
this.length++;
}
addAtIndex(index: number, val: number): void {
if (index < 0 || index > this.length) return;
if (index === 0) {
this.addAtHead(val);
return;
}
if (index === this.length) {
this.addAtTail(val);
return;
}
let current = this.head;
for (let i = 0; i< index - 1; i++) {
current = current!.next;
}
const newNode = new Node(val, current!.next, current);
current!.next!.prev = newNode;
current!.next = newNode;
this.length++;
}
deleteAtIndex(index: number): void {
if (index < 0 || index >= this.length) return;
if (index === 0) {
this.head = this.head!.next;
if (this.head) {
this.head.prev = null;
} else {
this.tail = null; // List became empty
}
this.length--;
return;
}
let current = this.head;
for (let i = 0; i < index; i++) {
current = current!.next;
}
if (current!.next) {
current!.next.prev = current!.prev;
} else {
this.tail = current!.prev; // If deleting the last node, update the tail.
}
if (current!.prev) {
current!.prev.next = current!.next;
}
this.length--;
}
}