-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.ts
54 lines (37 loc) · 859 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
44
45
46
47
48
49
50
51
52
53
54
type Node<T> = {
prev?: Node<T>;
value: T
}
export class Stack<T> {
public length: number;
private head?: Node<T>;
constructor() {
this.length = 0;
this.head = undefined;
}
pop() {
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;
this.head = head.prev
return head.value;
}
push(item: T) {
const node = {value: item} as Node<T>
this.length++;
if(!this.head) {
this.head = node;
return;
}
node.prev = this.head;
this.head = node;
}
peak() {
return this.head?.value;
}
}
const x = new Stack<number>;