C语言利用栈实现括号匹配
#include <stdlib.h>
#include <stdio.h>
#define MaxSize 50
#define true 1
#define false 0
typedef struct
{
char data[MaxSize];
int top;
}SqStack;
void IninStack(SqStack *S)
{
S->top=-1;
}
_Bool StackEmpty(SqStack *S)
{
if(S->top==-1)
return true;
else
return false;
}
_Bool Push(SqStack *S,char x)
{
if(S->top==MaxSize-1)
return false;
S->data[++S->top]= x;
return true;
}
_Bool Pop(SqStack *S,char * x)
{
if(S->top==-1)
return false;
*x=S->data[S->top];
S->top--;
return true;
}
_Bool Top(SqStack *S,char * x)
{
if(S->top==-1)
return false;
*x=S->data[S->top];
return true;
}
_Bool BracketsCheck(SqStack *S,char *str)
{
IninStack(S);
int i=0;
char s='\0';
while(str[i]!='\0')
{
switch(str[i])
{
case '(':
if(!Push(S,'(')) return false;
break;
case '{':
if(!Push(S,'{')) return false;
break;
case '[':
if(!Push(S,'[')) return false;
break;
case ')':
if(!Pop(S,&s)) return false;
if(s!='(') return false;
break;
case '}':
if(!Pop(S,&s)) return false;
if(s!='{') return false;
break;
case ']':
if(!Pop(S,&s)) return false;
if(s!='[') return false;
break;
default:
break;
}
i++;
}
if(!StackEmpty(S))
{
return false;
}
else
{
return true;
}
}
int main()
{
SqStack S;
char str[3]={'(',')',')','\0'};
if(!BracketsCheck(&S,str))
{
printf("匹配错误");
}
else printf("匹配成功");
return 0;
}