-
Notifications
You must be signed in to change notification settings - Fork 2
/
linked-list.ts
121 lines (90 loc) · 2.35 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import type { INode, ILinkedList, IIteratorLinkedList } from "../types/interfaces";
import Node from "./node";
import IteratorLinkedList from "./iterator-linked-list";
class LinkedList<T> implements ILinkedList<T> {
first: null | INode<T>;
last: null | INode<T>;
#total: number;
[Symbol.iterator](): IIteratorLinkedList<T> {
return new IteratorLinkedList(this);
}
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;
}
findNodeByValue(searchValue: T): null | undefined | INode<T> {
if (this.#total === 0) {
throw new Error(
"LinkedList is Empty, operation `findNodeByValue` is not supported!"
);
}
const iterator = this[Symbol.iterator]();
for (const node of iterator) {
if (node!.value === searchValue) return node;
}
return null;
}
display(): void {
if (this.#total === 0) {
throw new Error("LinkedList is Empty, operation `display` is not supported!");
}
const iterator = this[Symbol.iterator]();
for (const node of iterator) node!.displayNode();
}
}
export default LinkedList;