forked from RubenVerborgh/AsyncIterator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedlist.ts
44 lines (38 loc) · 988 Bytes
/
linkedlist.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
interface LinkedNode<V> {
value: V;
next: LinkedNode<V> | null;
}
/**
* A list with O(1) push and shift operations.
*/
export class LinkedList<V> {
private _length: number = 0;
private _head: LinkedNode<V> | null = null;
private _tail: LinkedNode<V> | null = null;
get length() { return this._length; }
get first() { return this._head?.value; }
get last() { return this._tail?.value; }
get empty() { return this._head === null; }
push(value: V) {
const node = { value, next: null } as LinkedNode<V>;
if (this._tail === null)
this._head = this._tail = node;
else
this._tail.next = this._tail = node;
this._length++;
}
shift(): V | undefined {
if (this._head === null)
return undefined;
const { value, next } = this._head;
this._head = next;
if (next === null)
this._tail = null;
this._length--;
return value;
}
clear() {
this._length = 0;
this._head = this._tail = null;
}
}