From 8094798c4687aaef25c7fc1cf2e13d453393bbe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aitor=20Fidalgo=20S=C3=A1nchez?= <64830228+aitorfi@users.noreply.github.com> Date: Thu, 14 Oct 2021 12:25:38 +0200 Subject: [PATCH] Fix unhandled EmptyStackException (#2606) --- Others/QueueUsingTwoStacks.java | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java index 104f6b92..cc39b29b 100644 --- a/Others/QueueUsingTwoStacks.java +++ b/Others/QueueUsingTwoStacks.java @@ -15,14 +15,14 @@ import java.util.Stack; class QueueWithStack { // Stack to keep track of elements inserted into the queue - private Stack inStack; + private Stack inStack; // Stack to keep track of elements to be removed next in queue - private Stack outStack; + private Stack outStack; /** Constructor */ public QueueWithStack() { - this.inStack = new Stack(); - this.outStack = new Stack(); + this.inStack = new Stack<>(); + this.outStack = new Stack<>(); } /** @@ -82,6 +82,24 @@ class QueueWithStack { public boolean isEmpty() { return (this.inStack.isEmpty() && this.outStack.isEmpty()); } + + /** + * Returns true if the inStack is empty. + * + * @return true if the inStack is empty. + */ + public boolean isInStackEmpty() { + return (inStack.size() == 0); + } + + /** + * Returns true if the outStack is empty. + * + * @return true if the outStack is empty. + */ + public boolean isOutStackEmpty() { + return (outStack.size() == 0); + } } /** @@ -118,7 +136,7 @@ public class QueueUsingTwoStacks { System.out.println(myQueue.isEmpty()); // Will print false System.out.println(myQueue.remove()); // Will print 1 - System.out.println(myQueue.peekBack()); // Will print NULL + System.out.println((myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL // instack: [] // outStack: [(top) 2, 3, 4]