File tree Expand file tree Collapse file tree 2 files changed +56
-1
lines changed Expand file tree Collapse file tree 2 files changed +56
-1
lines changed Original file line number Diff line number Diff line change @@ -46,6 +46,7 @@ Data structures covered so far -
46
46
- [ Graph] ( #graph )
47
47
- [ Queue] ( #queue )
48
48
- [ Linked List] ( #link-list )
49
+ - [ Stack] ( #stack )
49
50
50
51
# Contribution
51
52
Your contribution is highly appreciated. You can contribute in several ways -
@@ -242,3 +243,37 @@ Usage as spread operator
242
243
``` js
243
244
const items = [... list] // ['firstVal', 'Mid', 'xyz', 'secondVal']
244
245
```
246
+
247
+ # <a name =" stack " ></a > Stack (Linked List Implementation)
248
+
249
+ Import Stack data structure and create a list object.
250
+
251
+ ``` js
252
+ import { Stack } from ' @js-labs/data-structures/lib/ds' ;
253
+ // const { Stack } = require('@js-labs/data-structures/lib/ds')
254
+ const stack = new Stack ;
255
+ ```
256
+
257
+ Get size of the stack and check if the stack is empty
258
+
259
+ ``` js
260
+ stack .size () // 0
261
+ stack .isEmpty () // true
262
+ ```
263
+
264
+ Push items in the stack
265
+
266
+ ``` js
267
+ stack .push (' item1' );
268
+ stack .size () // 1
269
+
270
+ stack .push (' item2' );
271
+ stack .size () // 2
272
+ ```
273
+
274
+ Pop items from the stack
275
+
276
+ ``` js
277
+ stack .pop () // item2
278
+ stack .pop () // item1
279
+ ```
Original file line number Diff line number Diff line change @@ -9,31 +9,51 @@ export class Stack {
9
9
this [ _stack ] = new LinkedList ;
10
10
}
11
11
12
+ /**
13
+ * getter for _stack object
14
+ */
12
15
get stack ( ) {
13
16
return this [ _stack ] ;
14
17
}
15
18
19
+ /**
20
+ * Push an item on top of the stack.
21
+ * Ideally the insertFirst method of linked list is called to add the item in the first position in linked list
22
+ * @param {any } item
23
+ */
16
24
push ( item ) {
17
25
this [ _stack ] . insertFirst ( item ) ;
18
26
}
19
27
28
+ /**
29
+ * Pop the top item from the stack
30
+ * Ideally removeFirst method of stack is called
31
+ */
20
32
pop ( ) {
21
33
if ( ! this . isEmpty ( ) ) {
22
34
return this [ _stack ] . removeFirst ( ) . key ;
23
35
}
24
-
25
36
}
26
37
38
+ /**
39
+ * Returns the top item of the stack without popping it
40
+ */
27
41
peek ( ) {
28
42
if ( ! this . isEmpty ( ) ) {
29
43
return this [ _stack ] . head . key ;
30
44
}
31
45
}
32
46
47
+ /**
48
+ * Returns the size of the stack
49
+ */
33
50
size ( ) {
34
51
return this [ _stack ] . size ( ) ;
35
52
}
36
53
54
+ /**
55
+ * Checks if the stack is empty
56
+ */
37
57
isEmpty ( ) {
38
58
return this . size ( ) === 0 ;
39
59
}
You can’t perform that action at this time.
0 commit comments