//题目描述:输入一串字符串,仅含'(',')','[',']','{','}'六种字符,不含空格,且字符串以换行符结束,判断该字符串是否匹配。
//顺序栈
#include <stdio.h>
#include <stdlib.h>
#define STACK_CHAR_SIZE 100 //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间分配增量
typedef char SElemType;
typedef struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize; //当前存储空间容量
}SqStack;
void InitStack(SqStack &S) //建栈初始化
{
S.base=(SElemType *)malloc(STACK_CHAR_SIZE*sizeof(SElemType)); //分配空间,初始化操作
if(!S.base) exit(0);
S.top=S.base;
S.stacksize=STACK_CHAR_SIZE;
}
int StackEmpty(SqStack &S) //判断栈是否为空栈
{
if(S.top==S.base)
return 1;
else
return 0;
}
void ClearStack(SqStack &S) //销毁栈
{
S.base=S.top=NULL;
S.stacksize=0;
}
void push(SqStack &S,SElemType e) //进栈
{
if(S.top-S.base>=S.stacksize)
{
S.base=(SElemType *)realloc(S.base,(STACK_CHAR_SIZE+STACKINCREMENT)*sizeof(SElemType)); //扩充栈空间
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
}
void pop(SqStack &S,SElemType &e) //出栈
{
if(S.top==S.base) exit(0);
e=*--S.top;
}
void GetTop(SqStack &S,SElemType &e) //取栈顶元素
{
if(S.top==S.base) exit(0);
e=*(S.top-1);
}
int compare(SElemType a,SElemType b) //括号匹配
{
int key=0;
if(a=='(')
{
if(b==')') key=1;
}
else if(a=='[')
{
if(b==']') key=1;
}
else if(a=='{')
{
if(b=='}') key=1;
}
return key;
}
int main()
{
SqStack S;
char ch,e;
while(1)
{
InitStack(S);
ch=getchar();
while(ch!='\n')
{
if(ch=='(' || ch=='[' || ch=='{')
push(S,ch);
else
{
if(StackEmpty(S))
push(S,ch);
else
{
GetTop(S,e);
if(compare(e,ch)) //e为栈顶元素,ch为当前输入元素,当栈顶括号与当前括号匹配时,就出栈
pop(S,e);
else
push(S,ch);
}
}
ch=getchar();
}
if(StackEmpty(S))
printf("匹配\n");
else
printf("不匹配\n");
ClearStack(S);
}
return 0;
}