算法思想是检查字符串,如果是左括号就做入栈操作,如果遇到右括号就做出栈操作,相当于不断抵消左右括号,最后检查栈是否为空,为空则满足括号匹配检查。
代码如下:
//括号匹配检查
#include<stdio.h>
#include<stdlib.h>
typedef char elemtype;
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define Length 50
typedef struct
{
elemtype * base;
elemtype * top;
int stacksize;
}SqStack;
int Inistack(SqStack &s)
{
s.base = (elemtype *)malloc(STACK_INIT_SIZE * sizeof(elemtype));
if (!s.base)
exit(0);
s.top = s.base;
s.stacksize = STACK_INIT_SIZE;
return 1;
}
int push(SqStack &s, elemtype e)
{
if (s.top - s.base >= s.stacksize)
{
s.base = (elemtype *)realloc(s.base, (s.stacksize + STACKINCREMENT) * sizeof(elemtype));
if (!s.base)
exit(0);
s.top = s.base + s.stacksize;
s.stacksize += STACKINCREMENT;
}
*(s.top++) = e;
return 1;
}
int pop(SqStack &s)
{
if (s.top == s.base)
exit(0);
*(--s.top);
}
int Bracket_Matching_check(SqStack s,char a[])
{
int i = 0;
while (a[i] != '\0')
{
if (a[i] == '(')
{
push(s, a[i]);
}
if (a[i]==')')
{
pop(s);
}
i++;
}
if (s.top == s.base)
return 1;
else
return 0;
}
int main()
{
SqStack s;
Inistack(s);
char a[Length];
printf("请输入: //注意调至英文输入法\n");
scanf("%s", a);
if (Bracket_Matching_check(s, a))
printf("括号匹配正常!\n");
else
printf("括号匹配错误!\n");
system("pause");
}