File tree Expand file tree Collapse file tree 1 file changed +10
-0
lines changed
src/data-structures/stack Expand file tree Collapse file tree 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';
22
33export default class Stack {
44 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.
58 this . linkedList = new LinkedList ( ) ;
69 }
710
811 /**
912 * @return {boolean }
1013 */
1114 isEmpty ( ) {
15+ // The queue is empty in case if its linked list don't have tail.
1216 return ! this . linkedList . tail ;
1317 }
1418
@@ -17,23 +21,29 @@ export default class Stack {
1721 */
1822 peek ( ) {
1923 if ( this . isEmpty ( ) ) {
24+ // If linked list is empty then there is nothing to peek from.
2025 return null ;
2126 }
2227
28+ // Just read the value from the end of linked list without deleting it.
2329 return this . linkedList . tail . value ;
2430 }
2531
2632 /**
2733 * @param {* } value
2834 */
2935 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.
3038 this . linkedList . append ( value ) ;
3139 }
3240
3341 /**
3442 * @return {* }
3543 */
3644 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.
3747 const removedTail = this . linkedList . deleteTail ( ) ;
3848 return removedTail ? removedTail . value : null ;
3949 }
You can’t perform that action at this time.
0 commit comments