File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Stack {
2
+ constructor ( ) {
3
+ this . items = [ ] ;
4
+ }
5
+
6
+ // Add an item to the top of the stack
7
+ push ( item ) {
8
+ this . items . push ( item ) ;
9
+ }
10
+
11
+ // Remove and return the item at the top of the stack
12
+ pop ( ) {
13
+ if ( this . isEmpty ( ) ) {
14
+ throw new Error ( "Stack is empty" ) ;
15
+ }
16
+ return this . items . pop ( ) ;
17
+ }
18
+
19
+ // Return the item at the top of the stack without removing it
20
+ peek ( ) {
21
+ if ( this . isEmpty ( ) ) {
22
+ throw new Error ( "Stack is empty" ) ;
23
+ }
24
+ return this . items [ this . items . length - 1 ] ;
25
+ }
26
+
27
+ // Check if the stack is empty
28
+ isEmpty ( ) {
29
+ return this . items . length === 0 ;
30
+ }
31
+
32
+ // Return the number of items in the stack
33
+ size ( ) {
34
+ return this . items . length ;
35
+ }
36
+
37
+ // Empty the stack
38
+ clear ( ) {
39
+ this . items = [ ] ;
40
+ }
41
+ }
42
+
43
+ // Example usage:
44
+ const stack = new Stack ( ) ;
45
+ stack . push ( 10 ) ;
46
+ stack . push ( 20 ) ;
47
+ stack . push ( 30 ) ;
48
+ console . log ( stack . peek ( ) ) ; // 30
49
+ stack . pop ( ) ;
50
+ console . log ( stack . peek ( ) ) ; // 20
51
+
You can’t perform that action at this time.
0 commit comments