@@ -2,50 +2,47 @@ import LinkedList from '../linked-list/LinkedList';
2
2
3
3
export default class Queue {
4
4
constructor ( ) {
5
- // We're going to implement Queue based on LinkedList since this
6
- // structures a quite similar. Namely they both operates mostly with
7
- // with theirs beginning and the end. Compare enqueue/de-queue
8
- // operations of the Queue with append/prepend operations of LinkedList.
5
+ // We're going to implement Queue based on LinkedList since the two
6
+ // structures are quite similar. Namely, they both operate mostly on
7
+ // the elements at the beginning and the end. Compare enqueue/dequeue
8
+ // operations of Queue with append/deleteHead operations of LinkedList.
9
9
this . linkedList = new LinkedList ( ) ;
10
10
}
11
11
12
12
/**
13
13
* @return {boolean }
14
14
*/
15
15
isEmpty ( ) {
16
- // The queue is empty in case if its linked list don't have tail.
17
- return ! this . linkedList . tail ;
16
+ return ! this . linkedList . head ;
18
17
}
19
18
20
19
/**
20
+ * Read the element at the front of the queue without removing it.
21
21
* @return {* }
22
22
*/
23
23
peek ( ) {
24
24
if ( ! this . linkedList . head ) {
25
- // If linked list is empty then there is nothing to peek from.
26
25
return null ;
27
26
}
28
27
29
- // Just read the value from the end of linked list without deleting it.
30
28
return this . linkedList . head . value ;
31
29
}
32
30
33
31
/**
32
+ * Add a new element to the end of the queue (the tail of the linked list).
33
+ * This element will be processed after all elements ahead of it.
34
34
* @param {* } value
35
35
*/
36
36
enqueue ( value ) {
37
- // Enqueueing means to stand in the line. Therefore let's just add
38
- // new value at the beginning of the linked list. It will need to wait
39
- // until all previous nodes will be processed.
40
37
this . linkedList . append ( value ) ;
41
38
}
42
39
43
40
/**
41
+ * Remove the element at the front of the queue (the head of the linked list).
42
+ * If the queue is empty, return null.
44
43
* @return {* }
45
44
*/
46
45
dequeue ( ) {
47
- // Let's try to delete the last node from linked list (the tail).
48
- // If there is no tail in linked list (it is empty) just return null.
49
46
const removedHead = this . linkedList . deleteHead ( ) ;
50
47
return removedHead ? removedHead . value : null ;
51
48
}
0 commit comments