#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 50
typedef struct
{
char data[MAXSIZE];
int top;
} Stack;
void init_stack(Stack *s)
{
s->top = 0;
}
int pop(Stack *s, char *e)
{
if (s->top == 0)
{
return -1;
}
*e = s->data[--s->top];
return 0;
}
int push(Stack *s, char e)
{
if (s->top == MAXSIZE)
{
return -1;
}
s->data[s->top++] = e;
return 0;
}
int IsEmpty(Stack s)
{
if (s.top == 0)
return 1;
return 0;
}
char GetTopElem(Stack s)
{
if (s.top == 0)
return 0;
return s.data[--s.top];
}
int bracketCheck(char str[], int length)//栈的应用-括号匹配算法
{
Stack s;
char topElem;
init_stack(&s);
for (int i = 0; i < length; i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
{
push(&s, str[i]);
}
else
{
if (IsEmpty(s))
{
return 0;
}
pop(&s, &topElem);
if (str[i] == ')' && topElem != '(')
return 0;
if (str[i] == ']' && topElem != '[')
return 0;
if (str[i] == '}' && topElem != '{')
return 0;
}
}
return IsEmpty(s);
}
int main()
{ //测试用例:'[', ']','(', ')','{', '[',']', '}','(', ')','(', ')'
char str[] = {'[', ']','(', ')','{', '[',']', '}','(', ')','(', ')'};
int length=sizeof(str)/sizeof(str[0]);
int flag = bracketCheck(str, length);
if (flag)
{
printf("括号匹配成功!\n");
}
else
{
printf("括号匹配失败!\n");
}
system("pause");
return 0;
}