-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
55 lines (47 loc) · 1.44 KB
/
index.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
import {
DoublyLinkedList,
DoublyLinkedListNode,
} from "../doubly-linked-list/index.ts";
export interface CirularDoublyLinkedListNode<T>
extends DoublyLinkedListNode<T> {
previous: CirularDoublyLinkedListNode<T>;
next: CirularDoublyLinkedListNode<T>;
}
export class CirularDoublyLinkedListNode<T>
implements CirularDoublyLinkedListNode<T> {
previous: CirularDoublyLinkedListNode<T>;
next: CirularDoublyLinkedListNode<T>;
constructor(
value: T,
previous?: CirularDoublyLinkedListNode<T>,
next?: CirularDoublyLinkedListNode<T>
) {
this.value = value;
this.previous = previous ? previous : this;
this.next = next ? next : this;
}
}
export class CircularDoublyLinkedList<T> extends DoublyLinkedList<T> {
head?: CirularDoublyLinkedListNode<T>;
tail?: CirularDoublyLinkedListNode<T>;
addHead(value: T): CirularDoublyLinkedListNode<T> {
const node = new CirularDoublyLinkedListNode(value, this.tail, this.head);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
this.head = <CirularDoublyLinkedListNode<T>>(
this.addBefore(this.head, node)
);
}
return node;
}
addTail(value: T): CirularDoublyLinkedListNode<T> {
if (!this.tail) {
return this.addHead(value);
}
const node = new CirularDoublyLinkedListNode(value, this.tail, this.head);
this.tail = <CirularDoublyLinkedListNode<T>>this.addAfter(this.tail, node);
return node;
}
}