-
Notifications
You must be signed in to change notification settings - Fork 2
/
linked-list.ts
90 lines (67 loc) · 1.62 KB
/
linked-list.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
import type { INode, ILinkedList } from "../types/interfaces";
import Node from "./node";
class LinkedList<T> implements ILinkedList<T> {
first: null | INode<T>;
last: null | INode<T>;
#total: number;
constructor() {
this.first = null;
this.last = null;
this.#total = 0;
}
addFirst(valueForNewNode: T): number {
const newNode = new Node(valueForNewNode);
if (this.#total === 0) {
this.last = newNode;
} else if (this.first) {
this.first.prev = newNode;
newNode.next = this.first;
}
this.first = newNode;
this.#total++;
return this.#total;
}
add(valueForNewNode: T): number {
const newNode = new Node(valueForNewNode);
if (this.#total === 0) {
this.first = newNode;
} else if (this.last) {
newNode.prev = this.last;
this.last.next = newNode;
}
this.last = newNode;
this.#total++;
return this.#total;
}
deleteFirst(): INode<T> {
if (this.first === null) {
throw new Error("LinkedList is Empty, operation `deleteFirst` is not supported!");
}
const deletedFirstElement = this.first;
if (this.first.next) {
this.first = this.first.next;
this.first.prev = null;
} else {
this.first = null;
this.last = null;
}
this.#total--;
return deletedFirstElement;
}
deleteLast(): INode<T> {
if (this.last === null) {
throw new Error("LinkedList is Empty, operation `deleteLast` is not supported!");
}
const deletedElement = this.last;
if (this.last.prev) {
this.last = this.last.prev;
this.last.next = null;
} else {
this.first = null;
this.last = null;
}
this.#total--;
return deletedElement;
}
}
export default LinkedList;