/
index.ts
67 lines (58 loc) · 1004 Bytes
/
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
56
57
58
59
60
61
62
63
64
65
66
67
import { LinkedList } from 'dori.linkedlist'
/**
* Stack
*
* @template T - stack element type
*/
export class Stack<T> {
list = new LinkedList<T>()
/**
* whether stack is empty
*/
empty() {
return !this.list.size()
}
/**
* size of stack
*
* @returns {number}
*/
size() {
return this.list.size()
}
/**
* get the top element of stack, T = O(1)
*
* @returns {T | undefined}
*/
peek() {
const head = this.list.head()
return head ? head.value : null
}
/**
* push element to the stack, T = O(1)
*
* @param {T} value
* @returns {void}
*/
push(value: T) {
this.list.prepend(value)
}
/**
* pop top element of stack, T = O(1)
*
* @returns {T | null}
*/
pop() {
const head = this.list.remove((_, index) => index === 0)
return head ? head.value : null
}
/**
* transform to Array, T = O(n)
*
* @returns {T[]}
*/
toArray() {
return this.list.toArray().reverse()
}
}