File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Node {
2
+ constructor ( value , next = null ) {
3
+ this . value = value ;
4
+ this . next = next ;
5
+ }
6
+ }
7
+
8
+ class Queue {
9
+ #head;
10
+ #tail;
11
+ #length;
12
+
13
+ constructor ( ) {
14
+ this . #head = null ;
15
+ this . #tail = null ;
16
+ this . #length = 0 ;
17
+ }
18
+
19
+ /**
20
+ * Adds an element to the end of the queue.
21
+ * @param {* } value The element to be added.
22
+ * @returns {number } The new length of the queue.
23
+ */
24
+ enqueue ( value ) {
25
+ const node = new Node ( value ) ;
26
+
27
+ if ( this . isEmpty ( ) ) {
28
+ this . #head = node ;
29
+ this . #tail = node ;
30
+ } else {
31
+ this . #tail. next = node ;
32
+ this . #tail = node ;
33
+ }
34
+
35
+ return ++ this . #length;
36
+ }
37
+
38
+ /**
39
+ * Removes the element at the front of the queue.
40
+ * @returns {* } The element at the front of the queue.
41
+ */
42
+ dequeue ( ) {
43
+ if ( this . isEmpty ( ) ) {
44
+ return null ;
45
+ }
46
+
47
+ const currHead = this . #head;
48
+ this . #head = currHead . next ;
49
+ currHead . next = null ;
50
+ this . #length-- ;
51
+
52
+ if ( this . isEmpty ( ) ) {
53
+ this . #tail = null ;
54
+ }
55
+
56
+ return currHead . value ;
57
+ }
58
+
59
+ /**
60
+ * Checks if the queue is empty.
61
+ * @returns {boolean } Whether the queue is empty.
62
+ */
63
+ isEmpty ( ) {
64
+ return this . #length === 0 ;
65
+ }
66
+
67
+ /**
68
+ * Gets the number of elements in the queue.
69
+ * @returns {number } The number of elements in the queue.
70
+ */
71
+ get length ( ) {
72
+ return this . #length;
73
+ }
74
+ }
You can’t perform that action at this time.
0 commit comments