3
3
import java .util .Stack ;
4
4
import java .util .NoSuchElementException ;
5
5
6
+ /**
7
+ * A queue implementation using two stacks. This class provides methods to
8
+ * enqueue (add) elements to the end of the queue and dequeue (remove)
9
+ * elements from the front, while utilizing two internal stacks to manage
10
+ * the order of elements.
11
+ *
12
+ * @param <T> The type of elements held in this queue.
13
+ */
6
14
public class QueueByTwoStacks <T > {
7
15
8
- private Stack <T > enqueueStk ;
9
- private Stack <T > dequeueStk ;
16
+ private final Stack <T > enqueueStk ;
17
+ private final Stack <T > dequeueStk ;
10
18
11
- // Constructor initializes stacks and optionally fills the queue from an iterable
19
+ /**
20
+ * Constructor that initializes two empty stacks for the queue.
21
+ * The `enqueueStk` is used to push elements when enqueuing, and
22
+ * the `dequeueStk` is used to pop elements when dequeuing.
23
+ */
12
24
public QueueByTwoStacks () {
13
25
enqueueStk = new Stack <>();
14
26
dequeueStk = new Stack <>();
15
27
}
16
28
17
- // Add an item to the queue
29
+ /**
30
+ * Adds an element to the end of the queue. This method pushes the element
31
+ * onto the `enqueueStk`.
32
+ *
33
+ * @param item The element to be added to the queue.
34
+ */
18
35
public void put (T item ) {
19
36
enqueueStk .push (item );
20
37
}
21
38
22
- // Remove and return the first item from the queue
39
+ /**
40
+ * Removes and returns the element at the front of the queue.
41
+ * If `dequeueStk` is empty, it transfers all elements from
42
+ * `enqueueStk` to `dequeueStk` to maintain the correct FIFO
43
+ * (First-In-First-Out) order before popping.
44
+ *
45
+ * @return The element at the front of the queue.
46
+ * @throws NoSuchElementException If the queue is empty.
47
+ */
23
48
public T get () {
24
49
if (dequeueStk .isEmpty ()) {
25
50
while (!enqueueStk .isEmpty ()) {
@@ -32,12 +57,25 @@ public T get() {
32
57
return dequeueStk .pop ();
33
58
}
34
59
35
- // Get the number of elements in the queue
60
+ /**
61
+ * Returns the total number of elements currently in the queue.
62
+ * This is the sum of the sizes of both stacks.
63
+ *
64
+ * @return The number of elements in the queue.
65
+ */
36
66
public int size () {
37
67
return enqueueStk .size () + dequeueStk .size ();
38
68
}
39
69
40
- // Return string representation of the queue
70
+ /**
71
+ * Returns a string representation of the queue, showing the elements
72
+ * in the correct order (from front to back).
73
+ * The `dequeueStk` is first cloned, and then all elements from the
74
+ * `enqueueStk` are added to the cloned stack in reverse order to
75
+ * represent the queue accurately.
76
+ *
77
+ * @return A string representation of the queue.
78
+ */
41
79
@ Override
42
80
public String toString () {
43
81
Stack <T > tempStack = (Stack <T >) dequeueStk .clone ();
0 commit comments