-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.ts
54 lines (45 loc) · 1.15 KB
/
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
// from https://www.geeksforgeeks.org/how-to-create-a-stack-in-typescript-using-an-array/
export class Stack<T> {
private items: T[];
// Private array to store stack elements
constructor() {
this.items = [];
// Initialize the array as empty
//when a new stack is created
}
// Method to push an
// element onto the stack
push(element: T): void {
this.items.push(element);
}
// Method to pop an
// element from the stack
pop(): T | undefined {
return this.items.pop();
}
// Method to peek the top element
// of the stack without removing it
peek(): T | undefined {
return this.items[this.items.length - 1];
}
// Method to check
// if the stack is empty
isEmpty(): boolean {
return this.items.length === 0;
}
// Method to get
// the size of the stack
size(): number {
return this.items.length;
}
// Method to
// clear the stack
clear(): void {
this.items = [];
}
// Method to print
// the elements of the stack
print(): void {
console.log(this.items);
}
}