在此section中,我们学习了对于栈这一数据结构进行了应用,这一运用利用了线性表中最有优势的一点----容易排序,此代码将不同种的括号分到了不同的格子中,然后根据线性表的顺序进行验证,容易验证出其算式中的括号是否正确,有助于帮助我们更好的运算。
此应用有助于帮我们更好的体会其价值,帮助我们去更好的运用,提高主观能动性,同时有利于后期自己去设计代码。
在老师的代码中,我发现了,无论是正确与否,输出的数据都是一个数字:1或0,所以对于真实的代码测试过程中,它的可读性没有那么的高,所以我就给它的测试区域做了一些小小的改动,帮助我们更好的读取正确与否,提高代码的可操作性。
同时对于老师的代码是由bug的,在backerMatching函数中的末尾,无论它读取的字符是不是‘#’,返回的永远是true,所以我就做了一点小改动。
下面是我代码: 核心函数:bool bracketMatching(char* paraString, int paraLength)
{
CharStackPtr tempStack = charStackInit();
push(tempStack, '#');
char tempChar, tempPopedChar;
for(int i = 0; i < paraLength; i ++)
{
tempChar = paraString[i];
switch (tempChar)
{
case '(':
case '[':
case '{':
push(tempStack, tempChar);
break;
case ')':
tempPopedChar = pop(tempStack);
if(tempPopedChar != '(')
{
return false;
}
break;
case ']':
tempPopedChar = pop(tempStack);
if(tempPopedChar != '[')
{
return false;
}
break;
case '}':
tempPopedChar = pop(tempStack);
if(tempPopedChar != '{')
{
return false;
}
break;
default:
break;
}
}
tempPopedChar = pop(tempStack);
if(tempPopedChar != '#')
{
return false;
}
return true;
}
测试函数:
void brackerMatchingTest()
{
char* tempExpression = "[2 + (1 - 3)] * 4";
bool tempMatch = bracketMatching(tempExpression, 17);
printf("Is the expression '%s' bracket matching?rn", tempExpression, tempMatch);
if(tempMatch == TRUE)
{
printf("TRUErn");
}
else
{
printf("FALSErn");
}
tempExpression = "( ) )";
tempMatch = bracketMatching(tempExpression, 6);
printf("Is the expression '%s' bracket matching?rn", tempExpression, tempMatch);
if(tempMatch == TRUE)
{
printf("TRUErn");
}
else
{
printf("FALSErn");
}
tempExpression = "()()(())";
tempMatch = bracketMatching(tempExpression, 8);
printf("Is the expression '%s' bracket matching?rn", tempExpression, tempMatch);
if(tempMatch == TRUE)
{
printf("TRUErn");
}
else
{
printf("FALSErn");
}
tempExpression = "({}[])";
tempMatch = bracketMatching(tempExpression, 6);
printf("Is the expression '%s' bracket matching?rn", tempExpression, tempMatch);
if(tempMatch == TRUE)
{
printf("TRUErn");
}
else
{
printf("FALSErn");
}
tempExpression = ")(";
tempMatch = bracketMatching(tempExpression, 2);
printf("Is the expression '%s' bracket matching? %d rn", tempExpression, tempMatch);
if(tempMatch == TRUE)
{
printf("TRUErn");
}
else
{
printf("FALSErn");
}
}
测试结果:



