Exemple #1
0
bool areParenthesisBalanced(char exp[])
{
   int i = 0;

   struct sNode *stack = NULL;
   while(exp[i])
   {
      if(exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
        push(&stack, exp[i]);

      if(exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
      {

         if(stack == NULL)
           return 0;

         else if ( !isMatchingPair(pop(&stack), exp[i]) )
           return 0;
      }
      i++;
   }

   if(stack == NULL)
     return 1;
   else
     return 0;
}
Exemple #2
0
bool validateExpression(std::string expression) {
	int i = 0;
	Stack<char> parentheses;
	while (expression[i]) {
		if (expression[i] == '(') {
			parentheses.Push(expression[i]);
		}
		if (expression[i] == ')') {
			if (!isMatchingPair(parentheses.Peek(), expression[i]))
				return 0;
			else {
				parentheses.Pop();
			}
		}
		i++;
	}
	return parentheses.isEmpty();
}
Exemple #3
0
/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
   int i = 0;

   /* Declare an empty character stack */
   struct sNode *stack = NULL;

   /* Traverse the given expression to check matching parenthesis */
   while(exp[i])
   {
      /*If the exp[i] is a starting parenthesis then push it*/
      if(exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
        push(&stack, exp[i]);

      /* If exp[i] is a ending parenthesis then pop from stack and
          check if the popped parenthesis is a matching pair*/
      if(exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
      {

          /*If we see an ending parenthesis without a pair then return false*/
         if(stack == NULL)
           return 0;

         /* Pop the top element from stack, if it is not a pair
            parenthesis of character then there is a mismatch.
            This happens for expressions like {(}) */
         else if ( !isMatchingPair(pop(&stack), exp[i]) )
           return 0;
      }
      i++;
   }

   /* If there is something left in expression then there is a starting
      parenthesis without a closing parenthesis */
   if(stack == NULL)
     return 1; /*balanced*/
   else
     return 0;  /*not balanced*/
}