-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.ts
43 lines (36 loc) · 873 Bytes
/
Stack.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
type Node<T> = {
value: T,
prev: Node<T>,
}
export default class Stack<T> {
public length: number;
private head?: Node<T>;
constructor() {
this.head = undefined;
this.length = 0;
}
push(item: T): void {
const node = {value: item} as Node<T>;
this.length++;
if(!this.head){
this.head = node;
return;
}
node.prev = this.head;
this.head = node;
}
pop(): T | undefined {
this.length = Math.max(0, this.length-1);
if(this.length === 0){
const head = this.head;
this.head = undefined;
return head?.value;
}
const head = this.head as Node<T>;
this.head = head.prev;
return head.value;
}
peek(): T | undefined {
return this.head?.value
}
}