File tree 1 file changed +10
-0
lines changed
src/data-structures/stack
1 file changed +10
-0
lines changed Original file line number Diff line number Diff line change @@ -2,13 +2,17 @@ import LinkedList from '../linked-list/LinkedList';
2
2
3
3
export default class Stack {
4
4
constructor ( ) {
5
+ // We're going to implement Queue based on LinkedList since this
6
+ // structures a quite similar. Compare push/pop operations of the Stack
7
+ // with append/deleteTail operations of LinkedList.
5
8
this . linkedList = new LinkedList ( ) ;
6
9
}
7
10
8
11
/**
9
12
* @return {boolean }
10
13
*/
11
14
isEmpty ( ) {
15
+ // The queue is empty in case if its linked list don't have tail.
12
16
return ! this . linkedList . tail ;
13
17
}
14
18
@@ -17,23 +21,29 @@ export default class Stack {
17
21
*/
18
22
peek ( ) {
19
23
if ( this . isEmpty ( ) ) {
24
+ // If linked list is empty then there is nothing to peek from.
20
25
return null ;
21
26
}
22
27
28
+ // Just read the value from the end of linked list without deleting it.
23
29
return this . linkedList . tail . value ;
24
30
}
25
31
26
32
/**
27
33
* @param {* } value
28
34
*/
29
35
push ( value ) {
36
+ // Pushing means to lay the value on top of the stack. Therefore let's just add
37
+ // new value at the end of the linked list.
30
38
this . linkedList . append ( value ) ;
31
39
}
32
40
33
41
/**
34
42
* @return {* }
35
43
*/
36
44
pop ( ) {
45
+ // Let's try to delete the last node from linked list (the tail).
46
+ // If there is no tail in linked list (it is empty) just return null.
37
47
const removedTail = this . linkedList . deleteTail ( ) ;
38
48
return removedTail ? removedTail . value : null ;
39
49
}
You can’t perform that action at this time.
0 commit comments