-
Notifications
You must be signed in to change notification settings - Fork 1
/
sentinel-doubly-linked-list.ts
70 lines (59 loc) · 1.69 KB
/
sentinel-doubly-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
// TODO: Add tests
class SentinelDoublyLinkedNode {
public previous: SentinelDoublyLinkedNode | null;
public value: number | undefined;
public next: SentinelDoublyLinkedNode | null;
constructor(value?: number) {
this.previous = null;
this.value = value;
this.next = null;
}
}
class SentinelDoublyLinkedList {
public head: SentinelDoublyLinkedNode | null;
public tail: SentinelDoublyLinkedNode | null;
constructor(value: number) {
this.head = new SentinelDoublyLinkedNode();
this.tail = new SentinelDoublyLinkedNode();
this.head.next = this.tail;
this.tail.previous = this.head;
this.insertNode(this.tail.previous, value);
}
private insertNode(node: SentinelDoublyLinkedNode | null, value: number) {
const newNode = new SentinelDoublyLinkedNode(value);
newNode.previous = node;
newNode.next = node!.next;
newNode.previous!.next = newNode.next!.previous = newNode;
return newNode;
}
public addToBack(value: number) {
this.insertNode(this.tail!.previous, value);
}
public printForward() {
for (
let current = this.head!.next;
current !== this.tail;
current = this.head!.next
)
console.log(current!.value);
}
//private removeFromNode(deleteValue: SentinelDoublyLinkedNode | null) {}
public removeNode(deleteValue: number) {
for (
let remove = this.head!.next;
remove !== this.tail;
remove = this.head!.next
) {
if (remove!.value === deleteValue) {
//this.removeFromNode(remove);
return true;
}
}
}
}
const sll = new SentinelDoublyLinkedList(5);
sll.addToBack(6);
sll.addToBack(7);
sll.addToBack(8);
sll.addToBack(9);
sll.printForward();