File tree Expand file tree Collapse file tree 2 files changed +81
-1
lines changed
Data-Structures/Sequential Expand file tree Collapse file tree 2 files changed +81
-1
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change @@ -12,6 +12,10 @@ export default class StackLL<T> {
1212 this . length = 0 ;
1313 }
1414
15+ public getLength ( ) : number {
16+ return this . length ;
17+ }
18+
1519 public peek ( ) : T | null {
1620 return this . top ?. getValue ( ) || null ;
1721 }
@@ -50,7 +54,7 @@ export default class StackLL<T> {
5054 const value = this . top . getValue ( ) ; // Retrieve top value of stack
5155 this . top = this . top . getNext ( ) ; // Move top pointer to next node
5256
53- // On line 46 , the reference to the top most node of the stack is lost
57+ // On line 55 , the reference to the top most node of the stack is lost
5458 // The node is now floating in memory, waiting patiently for the garbage collector
5559
5660 -- this . length ;
You can’t perform that action at this time.
0 commit comments