-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackWithStaticArray.ts
58 lines (46 loc) · 1.15 KB
/
StackWithStaticArray.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
export class StackWithStaticArray<T> {
private stack: T[];
private maxSize: number;
private head: number;
constructor(maxSize: number) {
this.maxSize = maxSize;
this.stack = Array<T>(this.maxSize);
this.head = -1;
}
get size(): number {
return this.head + 1;
}
get capacity(): number {
return this.maxSize;
}
isEmpty(): boolean {
return this.head === -1;
}
isFull(): boolean {
return this.head === this.maxSize - 1;
}
push(data: T): void {
if (this.isFull()) {
throw new Error("Push to a full stack"); // stack overflow
}
this.head += 1;
this.stack[this.head] = data;
}
pop(): T | undefined {
if (this.isEmpty()) {
return undefined; // stack underflow
}
const popped_element: T = this.stack[this.head];
this.head -= 1;
return popped_element;
}
top(): T | undefined {
if (this.isEmpty()) {
return undefined;
}
return this.stack[this.head];
}
peek(): T | undefined {
return this.top();
}
}