用栈来实现括号匹配,每个栈有一个theArray和topOfStack,对于空栈其值为-1(这也就是空栈的初始化)。为了将某个元素压入到栈中,将topOfStack加1,然后置
theArray[topOfStack]=x。为了弹出栈元素,置pop函数的返回值为theArray[topOfStack],然后将topOfStack减1。
#include<stdio.h>
int isMatch(const char *code)
{
int a[100];
int i = -1; //初始化空栈
while(*code != '\0')
{
if(*code=='(' || *code=='{') //压栈
a[++i] = *code;
else
if(*code==')')
if(a[i]=='(')
i--; //出栈
else
return -1;
else
if(*code=='}')
if(a[i]=='{')
i--; //出栈
else
return -1;
code++;
}
if(i==-1) //栈已空说明全部匹配
return 0;
else
return -1;
}
int main(int argc,char *argv[])
{
char a[] = "({})(({()}))";
printf("%d\n",isMatch(a));
return 0;
}