Skip to content

Commit 8094798

Browse files
authored
Fix unhandled EmptyStackException (TheAlgorithms#2606)
1 parent b83bb01 commit 8094798

1 file changed

Lines changed: 23 additions & 5 deletions

File tree

Others/QueueUsingTwoStacks.java

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@
1515
class QueueWithStack {
1616

1717
// Stack to keep track of elements inserted into the queue
18-
private Stack inStack;
18+
private Stack<Object> inStack;
1919
// Stack to keep track of elements to be removed next in queue
20-
private Stack outStack;
20+
private Stack<Object> outStack;
2121

2222
/** Constructor */
2323
public QueueWithStack() {
24-
this.inStack = new Stack();
25-
this.outStack = new Stack();
24+
this.inStack = new Stack<>();
25+
this.outStack = new Stack<>();
2626
}
2727

2828
/**
@@ -82,6 +82,24 @@ public Object peekBack() {
8282
public boolean isEmpty() {
8383
return (this.inStack.isEmpty() && this.outStack.isEmpty());
8484
}
85+
86+
/**
87+
* Returns true if the inStack is empty.
88+
*
89+
* @return true if the inStack is empty.
90+
*/
91+
public boolean isInStackEmpty() {
92+
return (inStack.size() == 0);
93+
}
94+
95+
/**
96+
* Returns true if the outStack is empty.
97+
*
98+
* @return true if the outStack is empty.
99+
*/
100+
public boolean isOutStackEmpty() {
101+
return (outStack.size() == 0);
102+
}
85103
}
86104

87105
/**
@@ -118,7 +136,7 @@ public static void main(String args[]) {
118136
System.out.println(myQueue.isEmpty()); // Will print false
119137

120138
System.out.println(myQueue.remove()); // Will print 1
121-
System.out.println(myQueue.peekBack()); // Will print NULL
139+
System.out.println((myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL
122140
// instack: []
123141
// outStack: [(top) 2, 3, 4]
124142

0 commit comments

Comments
 (0)