C语言利用栈的“先进后出”的思想,实现括号匹配的问题,源代码如下所示:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 1024
typedef char ElemType;
typedef struct sqstack
{
ElemType Elems[MAX_LEN];
int top; /*栈顶元素的下标,栈的元素个数为top+1*/
}Sqstack;
ElemType GetTop(Sqstack *s);
Sqstack *InitStack();
ElemType Pop(Sqstack *s);
int Push(Sqstack *s,ElemType data);
int StackIsEmpty(Sqstack *s);
int chioce();
int main()
{
chioce();
return 0;
}
/*初始化一个顺序栈*/
Sqstack *InitStack()
{
Sqstack *s = malloc(sizeof(*s));
s->top = -1;
return s;
}
/*判断一个栈是否为空。如果为空,返回1,否则返回0*/
int StackIsEmpty(Sqstack *s)
{
if(s)
{
return s->top == -1;
}
return -1;
}
/*入栈,压栈*/
int Push(Sqstack *s,ElemType data)
{
if(s)
{
s->Elems[++s->top] = data;
return 0;
}
return -1;
}
/*出栈*/
ElemType Pop(Sqstack *s)
{
if(s)
{
return s->Elems[s->top--];
}
}
/*返回栈顶元素的值,但不是出栈*/
ElemType GetTop(Sqstack *s)
{
if(s)
{
return s->Elems[s->top];
}
}
int chioce()
{
Sqstack *stack = InitStack(); //初始化栈
char str[256]; //字符型数据
gets(str); //输入字符
int num = 0;
int i=0;
while(str[i] != '\0')
{
if(str[i]=='(' || str[i]=='[' || str[i]=='{')
{
Push(stack,str[i]); //入栈
num = 1;
}
else if(str[i]==')' || str[i]==']' || str[i]=='}')
{
if(StackIsEmpty(stack)) //如果栈为空
{
printf("brackets match false\n");
return 0;
}
if(str[i]==')' && GetTop(stack)=='(' || str[i]==']' && GetTop(stack)=='['
|| str[i]=='}' && GetTop(stack)=='{') //括号匹配
{
Pop(stack); //出栈
num = 1;
}
else
{
printf("brackets match false\n");
return 0;
}
}
i++;
}
if(num == 0)
{
printf("no bracket\n");
}
else
{
if(StackIsEmpty(stack)) //当栈为空
{
printf("brackets match true\n");
}
else
{
printf("brackets match false\n");
}
}
return 0;
}