1
+ export default class Stack < T > {
2
+ private length : number ;
3
+ private values : Array < T > ;
4
+
5
+ constructor ( ) {
6
+ this . length = 0 ;
7
+ this . values = new Array < T > ( ) ;
8
+ }
9
+
10
+ public getLength ( ) : number {
11
+ return this . length ;
12
+ }
13
+
14
+ public peek ( ) : T | null {
15
+ return this . values [ this . length - 1 ] || null ;
16
+ }
17
+
18
+ public push ( value : T ) : boolean {
19
+ this . values [ this . length ] = value ;
20
+ ++ this . length ;
21
+ return true ;
22
+ }
23
+
24
+ public pop ( ) {
25
+ const value = this . values [ this . length - 1 ] ;
26
+ delete this . values [ this . length - 1 ] ;
27
+ -- this . length ;
28
+ return value ;
29
+ }
30
+ }
31
+
32
+ function printStack ( stack : Stack < any > ) {
33
+ console . log ( JSON . stringify ( stack ) ) ;
34
+ }
35
+
36
+ function printPopStack ( stack : Stack < any > ) {
37
+ console . log ( 'Popped:' , stack . pop ( ) ) ;
38
+ }
39
+
40
+ function printPeekStack ( stack : Stack < any > ) {
41
+ console . log ( 'Peeking... Found' , stack . peek ( ) ) ;
42
+ }
43
+
44
+ //---------------------------------------------------------------------
45
+ // ---------- MAIN PROGRAM ----------
46
+ //---------------------------------------------------------------------
47
+ if ( import . meta. main ) {
48
+
49
+ const ATLA = new Stack < string > ( ) ;
50
+
51
+ printPeekStack ( ATLA ) ;
52
+ ATLA . push ( 'Sokka' ) ;
53
+ ATLA . push ( 'Katara' ) ;
54
+ printPeekStack ( ATLA ) ;
55
+ ATLA . push ( 'Aang' ) ;
56
+ ATLA . push ( 'Appa' ) ;
57
+
58
+ printStack ( ATLA ) ;
59
+
60
+ printPopStack ( ATLA ) ;
61
+
62
+ printStack ( ATLA ) ;
63
+
64
+ printPopStack ( ATLA ) ;
65
+ printPopStack ( ATLA ) ;
66
+ printPopStack ( ATLA ) ;
67
+
68
+ printStack ( ATLA ) ;
69
+
70
+ ATLA . push ( 'Zuko' ) ;
71
+ ATLA . push ( 'Iroh' ) ;
72
+
73
+ printStack ( ATLA ) ;
74
+
75
+ // RUN: deno run Data-Structures/Sequential/Stack.ts
76
+ }
0 commit comments