Repository: TheAlgorithms/Java
Pull request #5625 (2024-10-07 09:44:23)

Add `StackUsingTwoQueues.java` new algorithm
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5625?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `89.47368%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 54.78%. Comparing base [(`ee6cd64`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/ee6cd648bc4ea9e929548b8c93d841baf173925b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`eee98ed`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/eee98ed340ea58c6b9c66f7295a7c6d05eb15749?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5625?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [.../com/thealgorithms/stacks/StackUsingTwoQueues.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5625?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fstacks%2FStackUsingTwoQueues.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zdGFja3MvU3RhY2tVc2luZ1R3b1F1ZXVlcy5qYXZh) | 89.47% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5625?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5625      +/-   ##
============================================
+ Coverage     54.73%   54.78%   +0.04%     
- Complexity     3453     3461       +8     
============================================
  Files           538      539       +1     
  Lines         15583    15602      +19     
  Branches       2961     2962       +1     
============================================
+ Hits           8530     8547      +17     
- Misses         6695     6696       +1     
- Partials        358      359       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5625?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 9fb11129..7a1bb728 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -569,6 +569,7 @@
             * [PrefixToInfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java)
             * [SortStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/SortStack.java)
             * [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java)
+            * [StackUsingTwoQueues](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/StackUsingTwoQueues.java)
           * strings
             * [AhoCorasick](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/AhoCorasick.java)
             * [Alphabetical](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Alphabetical.java)
@@ -1032,6 +1033,7 @@
             * [PrefixToInfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java)
             * [SortStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/SortStackTest.java)
             * [StackPostfixNotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java)
+            * [StackUsingTwoQueuesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/StackUsingTwoQueuesTest.java)
           * strings
             * [AhoCorasickTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java)
             * [AlphabeticalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java)
diff --git a/src/main/java/com/thealgorithms/stacks/StackUsingTwoQueues.java b/src/main/java/com/thealgorithms/stacks/StackUsingTwoQueues.java
new file mode 100644
index 00000000..5b1ca5d1
--- /dev/null
+++ b/src/main/java/com/thealgorithms/stacks/StackUsingTwoQueues.java
@@ -0,0 +1,91 @@
+package com.thealgorithms.stacks;
+
+import java.util.LinkedList;
+import java.util.NoSuchElementException;
+import java.util.Queue;
+
+/**
+ * A class that implements a stack using two queues.
+ * This approach ensures that the stack's LIFO (Last In, First Out) behavior
+ * is maintained by utilizing two queues for storage.
+ * The mainQueue is used to store the elements of the stack, while the tempQueue
+ * is used to temporarily store elements during the push operation.
+ */
+public class StackUsingTwoQueues {
+
+    private Queue<Integer> mainQueue;
+    private Queue<Integer> tempQueue;
+
+    /**
+     * Constructs an empty stack using two queues.
+     */
+    public StackUsingTwoQueues() {
+        mainQueue = new LinkedList<>();
+        tempQueue = new LinkedList<>();
+    }
+
+    /**
+     * Pushes an element onto the top of the stack.
+     * The newly pushed element becomes the top of the stack.
+     *
+     * @param item The element to be pushed onto the stack.
+     */
+    public void push(int item) {
+        tempQueue.add(item);
+
+        // Move all elements from the mainQueue to tempQueue to maintain LIFO order
+        while (!mainQueue.isEmpty()) {
+            tempQueue.add(mainQueue.remove());
+        }
+
+        // Swap the names of the two queues
+        Queue<Integer> swap = mainQueue;
+        mainQueue = tempQueue;
+        tempQueue = swap; // tempQueue is now empty
+    }
+
+    /**
+     * Removes and returns the element at the top of the stack.
+     * Throws an exception if the stack is empty.
+     *
+     * @return The element at the top of the stack.
+     * @throws NoSuchElementException if the stack is empty.
+     */
+    public int pop() {
+        if (mainQueue.isEmpty()) {
+            throw new NoSuchElementException("Stack is empty");
+        }
+        return mainQueue.remove();
+    }
+
+    /**
+     * Returns the element at the top of the stack without removing it.
+     * Returns null if the stack is empty.
+     *
+     * @return The element at the top of the stack, or null if the stack is empty.
+     */
+    public Integer peek() {
+        if (mainQueue.isEmpty()) {
+            return null;
+        }
+        return mainQueue.peek();
+    }
+
+    /**
+     * Returns true if the stack is empty.
+     *
+     * @return true if the stack is empty; false otherwise.
+     */
+    public boolean isEmpty() {
+        return mainQueue.isEmpty();
+    }
+
+    /**
+     * Returns the number of elements in the stack.
+     *
+     * @return The size of the stack.
+     */
+    public int size() {
+        return mainQueue.size();
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/StackUsingTwoQueuesTest.java b/src/test/java/com/thealgorithms/stacks/StackUsingTwoQueuesTest.java
new file mode 100644
index 00000000..a7e24421
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/StackUsingTwoQueuesTest.java
@@ -0,0 +1,70 @@
+package com.thealgorithms.stacks;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class StackUsingTwoQueuesTest {
+
+    private StackUsingTwoQueues stack;
+
+    @BeforeEach
+    public void setUp() {
+        stack = new StackUsingTwoQueues();
+    }
+
+    @Test
+    public void testPushAndPeek() {
+        stack.push(1);
+        stack.push(2);
+        stack.push(3);
+        assertEquals(3, stack.peek());
+    }
+
+    @Test
+    public void testPop() {
+        stack.push(1);
+        stack.push(2);
+        stack.push(3);
+        assertEquals(3, stack.pop());
+        assertEquals(2, stack.pop());
+        assertEquals(1, stack.pop());
+    }
+
+    @Test
+    public void testPeek() {
+        stack.push(10);
+        stack.push(20);
+        assertEquals(20, stack.peek());
+        stack.pop();
+        assertEquals(10, stack.peek());
+    }
+
+    @Test
+    public void testIsEmpty() {
+        assertTrue(stack.isEmpty());
+        stack.push(1);
+        assertFalse(stack.isEmpty());
+        stack.pop();
+        assertTrue(stack.isEmpty());
+    }
+
+    @Test
+    public void testSize() {
+        assertEquals(0, stack.size());
+        stack.push(1);
+        stack.push(2);
+        assertEquals(2, stack.size());
+        stack.pop();
+        assertEquals(1, stack.size());
+    }
+
+    @Test
+    public void testPeekEmptyStack() {
+        assertNull(stack.peek());
+    }
+}