So I wrote this code to determine if an expression has balanced brackets in a stack:
public static boolean isBalanced(String expr) {
StringStack stack = new StringStackRefBased();
try{
for (int i = 0; i<expr.length(); i++){
if (expr.charAt(i) == ('(')){
stack.push("(");
} else if (expr.charAt(i) == (')')){
stack.pop();
}
}
if (stack.isEmpty()){
return true;
} else {
return false;
}
} catch (StringStackException e) {
return false;
}
}
The problem is that the stack keeps on returning false even if the expression has balanced parentheses so what's wrong with my code?
Here's the code for StringStackRefBased
public class StringStackRefBased implements StringStack {
private StringNode head;
public boolean isEmpty(){
return head == null;
}
public void push(String item) throws StringStackException{
head = new StringNode(item);
}
public String pop() throws StringStackException{
String result = null;
if(isEmpty()){
throw new StringStackException("Empty Stack");
}
head.next = head;
return head.toString();
}
public String peek() throws StringStackException{
if (isEmpty()){
throw new StringStackException("Stack underflow");
}
return head.toString();
}
}