diff --git a/Misc/BalancingBracketsUsingStack.java b/Misc/BalancingBracketsUsingStack.java new file mode 100644 index 000000000000..5df2d3546942 --- /dev/null +++ b/Misc/BalancingBracketsUsingStack.java @@ -0,0 +1,123 @@ +import java.util.Scanner; + +public class BalancedParan +{ + static class stack + { + int top=-1; //top refers to the top most value of the stack + char items[] = new char[100]; //Stack array + + void push(char x) + { + if (top == 99) + { + System.out.println("Stack full"); + } + else + { + items[++top] = x; + } + } + + char pop() + { + if (top == -1) + { + System.out.println("Underflow error"); + return '\0'; + } + else + { + char element = items[top]; + top--; + return element; + } + } + + boolean isEmpty() + { + return (top == -1) ? true : false; + } + } + + /* Returns true if character1 and character2 + are matching left and right Parenthesis */ + static boolean isMatchingPair(char character1, char character2) + { + if (character1 == '(' && character2 == ')') + return true; + else if (character1 == '{' && character2 == '}') + return true; + else if (character1 == '[' && character2 == ']') + return true; + else + return false; + } + + /* Return true if expression has balanced + Parenthesis */ + static boolean areParenthesisBalanced(char exp[]) + { + /* Declare an empty character stack */ + stack st=new stack(); + + /* Traverse the given expression to + check matching parenthesis */ + for(int i=0;i " + endPole); // Result Printing