#include<stdio.h>
#include<stdlib.h>
int main()
{
void BracketMatch();
BracketMatch();
}
typedef char ElemType;
typedef struct Stack
{
int top;
int MaxSize;
ElemType *stack;
}Stack;
void Creat(Stack*s , int m)
{
if(m<0)
{
printf("%d is negtive!",m);
return;
}
s->top=-1;
s->MaxSize=m;
s->stack=(ElemType*)malloc(sizeof(ElemType)*m);
}//Creat a stack
void Push(Stack *s, ElemType data)
{
if(s->top==s->MaxSize-1)
{
printf("The stack is full!");
return;
}
s->top++;
s->stack[s->top]=data;
}//Push data in the stack s
ElemType Pop(Stack *s)
{
ElemType temp;
if( s->top<-1)
{
printf("The stack is NULL!");
return;
}
temp=s->stack[s->top];
s->top--;
return temp;
}//Pop the top element of the stack
void BracketMatch()
{
int n=20;
int i=0;
char str[n];
char ch;
printf("请输入一个算术表达式(%d字符以内)\n",n);
scanf("%s",str);
Stack *s=(Stack*)malloc(sizeof(Stack));
Creat(s,n);//creat a stack of n elements
while(str[i]!='\0')
{
if(str[i]=='(' ||str[i]=='{' ||str[i]=='[' )
Push(s,str[i]);
if(str[i]==')')
{
ch=Pop(s);
if(ch!='(')
{ printf("Match failure!\n");return; }
}
if(str[i]==']')
{
ch=Pop(s);
if(ch!='[')
{ printf("Match failure!\n");return; }
}
if(str[i]=='}')
{
ch=Pop(s);
if(ch!='{')
{ printf("Match failure!\n");return; }
}
i++;
}
if(s->top==-1) //最后堆栈有无元素判断
printf("Match Successfully!\n");
else
printf("Match failure!\n");
}