//用顺序栈实现匹配括号功能
#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 100
typedef char datatype;
typedef struct //定义数据结构
{
datatype data[MAXSIZE];
int top;
}SeqStack;
SeqStack *InitStack()
{
SeqStack *s;
s=(SeqStack *)malloc(sizeof(SeqStack));
s->top=-1;
return s;
}
SeqStack *Push(SeqStack *s,datatype x) //入栈
{
if(s->top==MAXSIZE-1)
{
printf("The stack is overflow!/n");
return NULL;
}
else
{
s->top++;
s->data[s->top]=x;
return s;
}
}
datatype Pop(SeqStack *s) //出栈
{
if(s->top==-1)
{
printf("The stack is empty!/n");
return NULL;
}
else
{
s->top--;
return s->data[s->top+1];
}
}
datatype GetTop(SeqStack *s) //取出栈顶
{
if(s->top==-1)
{
printf("The stack is empty!/n");
return NULL;
}
else
{
return s->data[s->top];
}
}
bool StackEmpty(SeqStack *s) //判断是否是空栈
{
if(s->top==-1)
return true;
else
return false;
}
SeqStack *ClearStack(SeqStack *s) //清除栈
{
if(s!=NULL)
{
free(s);
printf("栈空间释放完毕!/n");
s=NULL;
return s;
}
else
{
printf("栈为空!/n");
return s;
}
}
bool match(SeqStack *s,char c[])
{
int i=0;
while(c[i]!='/0')
{
switch(c[i])
{
case '{':
case '[':
case '(': Push(s,c[i]);break;
case ')':
if(!StackEmpty(s) && GetTop(s)=='(')
{
Pop(s);break;
}
else
return false;
case ']':
if(!StackEmpty(s) && GetTop(s)=='[')
{
Pop(s);break;
}
else
return false;
case '}':
if(!StackEmpty(s) && GetTop(s)=='{')
{
Pop(s);break;
}
else
return false;
}
i++;
}
return (StackEmpty(s));
}
int main(int argc, char* argv[])
{
SeqStack *s;
s=InitStack();
char cc[50];//"3*(4-{5+2}*3)#";
int ch;
for(int i=0;(i<50) && ((ch=getchar()) != '/n');i++)
{
cc[i]=(char)ch;
}
if(match(s,cc))
printf("匹配!/n");
else
printf("不匹配!/n");
s=ClearStack(s);
return 0;
}