📜  数据结构|杂项|问题4

📅  最后修改于: 2021-06-29 18:36:04             🧑  作者: Mango

检查算术表达式是否具有平衡的括号的最佳数据结构是(GATE CS 2004)

(一)排队
(B)堆叠
(C)
(D)清单答案: (B)
说明:括号[] {}()有三种类型。下面是一个包含所有三种类型的括号的arbit c代码段。

void func(int c, int a[])
{
   return  ((c +2)  + arr[(c-2)]) ; 
}

堆栈是检查左括号和右括号是否平衡的直接选择。这是执行相同操作的算法。

/*Return 1 if expression has balanced parentheses */
bool areParenthesesBalanced(expression )
{ 
   for each character in expression
   {
      if(character == ’(’ || character == ’{’ || character == ’[’) 
        push(stack, character);
      if(character == ’)’ || character == ’}’ || character == ’]’) 
      {
         if(isEmpty(stack))  
           return 0; /*We are seeing a right parenthesis  
                       without a left pair*/
  
         /* Pop the top element from stack, if it is not a pair
             bracket of character then there is a mismatch. 
             This will happen for expressions like {(}) */
         else if (! isMatchingPair(pop(stack), character) ) 
           return 0;   
      }
   }
    
   if(isEmpty(stack))
     return 1; /*balanced*/
   else  
     return 0;  /*not balanced*/   
} /* End of function to check parentheses */
  
/* Returns 1 if character1 and character2 are matching left
   and right parentheses */
bool isMatchingPair(character1, character2)
{
   if(character1 == ‘(‘ && character2 == ‘)’)
     return 1;
   else If(character1 == ‘{‘ && character2 == ‘}’)
     return 1;
   else If(character1 == ‘[‘ && character2 == ‘]’)
     return 1;
   else 
     return 0;
}

这个问题的测验