-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.ts
More file actions
40 lines (32 loc) · 715 Bytes
/
Stack.ts
File metadata and controls
40 lines (32 loc) · 715 Bytes
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
export class Node<T> {
value: T;
next: Node<T> | null;
constructor(value: T) {
this.value = value;
this.next = null;
}
}
export class Stack<T> {
#top: Node<T> | null = null;
#size = 0;
push(value: T) {
const node = new Node(value); // Create a new node
node.next = this.#top; // Assign the next to the old top
this.#top = node; // Point the top to the new node
this.#size++;
}
pop(): T | null {
if (this.#size == 0) return null;
const oldTop = this.#top!;
if (this.#size == 1) {
this.#top = null;
} else {
this.#top = oldTop!.next;
}
this.#size--;
return oldTop.value;
}
get size(): number {
return this.#size;
}
}