From feecc59268fda5e3f7c944443239cb3f3349bac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aitor=20Fidalgo=20S=C3=A1nchez?= Date: Wed, 13 Oct 2021 20:44:43 +0200 Subject: [PATCH] Fixed unhandled EmptyStackException --- Others/QueueUsingTwoStacks.java | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/Others/QueueUsingTwoStacks.java b/Others/QueueUsingTwoStacks.java index 104f6b922088..cc39b29b55d0 100644 --- a/Others/QueueUsingTwoStacks.java +++ b/Others/QueueUsingTwoStacks.java @@ -15,14 +15,14 @@ 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 @@ public Object peekBack() { 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 static void main(String args[]) { 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]