栈的应用——括号匹配
程序员文章站
2022-07-14 23:13:42
...
//括号匹配问题
void MatchBrackets(char *buf, int len)
{
Stack s;
StackInit(&s);
int i = 0;
assert(buf);
for (i = 0; i < len; i++)
{
//如果是左括号,则将左括号入栈
if (('(' == buf[i]) ||
('[' == buf[i]) ||
('{' == buf[i]))
{
StackPush(&s, buf[i]);
}
//如果是右括号,则与栈顶元素比较,如果匹配,则出栈进行下轮
//若不匹配则直接退出
if ((')' == buf[i]) ||
(']' == buf[i]) ||
('}' == buf[i]))
{
if (0 == EmptyStack(&s))
{
printf("不匹配,右括号多于左括号\n");
return;
}
else
{
switch (buf[i])
{
case ')':
if ('(' == StackTop(&s))
{
StackPop(&s);
break;
}
else
{
printf("不匹配,左右括号次序不匹配\n");
return;
}
case ']':
if ('[' == StackTop(&s))
{
StackPop(&s);
break;
}
else
{
printf("不匹配,左右括号次序不匹配\n");
return;
}
case '}':
if ('{' == StackTop(&s))
{
StackPop(&s);
break;
}
else
{
printf("不匹配,左右括号次序不匹配\n");
return;
}
default:
return;
}
}
}
}
//判断栈是否为空
if (0 == EmptyStack(&s))
{
//若栈为空则匹配
printf("括号匹配\n");
return;
}
//栈不为空
printf("不匹配,左括号多于右括号\n");
return;
}
test.c
//测试括号匹配问题
test1()
{
char buf1[] = "(())abc{[(])}"; //左右括号次序不匹配
char buf2[] = "(()))abc{[]}"; //右括号多于左括号
char buf3[] = "(()()abc{[]}"; //左括号多于右括号
char buf4[] = "(())abc{[]()}"; //匹配正确
MatchBrackets(buf1, strlen(buf1));
MatchBrackets(buf2, strlen(buf2));
MatchBrackets(buf3, strlen(buf3));
MatchBrackets(buf4, strlen(buf4));
}
int main()
{
test1();
system("pause");
return 0;
}