检查算术表达式是否具有平衡括号的最佳数据结构是 (GATE CS 2004)
(一)队列
(二)堆栈
(C)树
(四)清单答案:(乙)
说明:括号 [ ] { } () 一共有三种。下面是一个仲裁 c 代码段,它具有所有三种类型的括号。
void func(int c, int a[])
{
return ((c +2) + arr[(c-2)]) ;
}
Stack 是检查左右括号是否平衡的直接选择。这是一个执行相同操作的算法。
/*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;
}
这个问题的测验