#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACK_INCRASE_SIZE 20
enum State{ERR,OK,FAILED};
typedef char SElemType;
typedef struct tag_Stack //此空递增
{
SElemType* pbase; //栈底指针
SElemType* ptop; //栈顶指针
int stacksize; //当前所有可用栈空间(包含已使用的)
}SqStack;
void InitStack(SqStack* ps)
{
ps->pbase = (SElemType*)calloc(STACK_INIT_SIZE,sizeof(SElemType)); //分配失败处理略
ps->ptop = ps->pbase;
ps->stacksize = STACK_INIT_SIZE;
}
void push(SqStack* ps,SElemType* pdata)
{
if(ps->ptop - ps->pbase >= ps->stacksize) //判断是否栈溢出(允许范围)
{
ps->pbase = (SElemType*)realloc(ps->pbase,(ps->stacksize+STACK_INCRASE_SIZE)*sizeof(SElemType));
//分配失败处理略
ps->ptop = ps->stacksize + ps->pbase;
ps->stacksize += STACK_INCRASE_SIZE;
}
*ps->ptop++ = *pdata; //有覆盖吧? 这是写入一个字串阿,不是字串 细细品味一哈
}
enum State pop(SqStack* ps,SElemType* pdata) //出栈pdata
{
if(ps->ptop == ps->pbase) return ERR;
*pdata = *(ps->ptop-1);
*(ps->ptop-1) = 0; //为了监视直观写此语句,正式运行时不需要,浪费效率
ps->ptop--;
return OK;
}
enum State GetAtTop(SqStack* ps,SElemType* pdata)
{
if(ps->ptop == ps->pbase) return ERR;
*pdata = *(ps->ptop-1);
return OK;
}
int IsStackEmpty(SqStack* ps)
{
if(ps->ptop == ps->pbase) return 1;
return 0;
}
int IsPipei(char ch1,char ch2)
{
switch(ch1)
{
case '[':
if(']'==ch2) return 1;
break;
case '(':
if(')'==ch2) return 1;
break;
case '{':
if('}'==ch2) return 1;
break;
default:
break;
}
return 0;
}
enum State CheckKuohu(SqStack* ps,char* pd)
{
int l = 0, i = 0;
char* ptmp = NULL,buf = 0;
ptmp = pd;
push(ps,(SElemType*)pd++);
do
{
SElemType tmp2 = 0;
GetAtTop(ps,&tmp2); //栈顶元素保存到tmp2
if(IsPipei(tmp2,(char)*pd)) //有点不规范,发生截断
{
pop(ps,&buf); //若匹配,则弹出
}
else
{
push(ps,(SElemType*)pd);
}
pd++;
}while(*pd);
if(IsStackEmpty(ps)) return OK;
return FAILED;
}
void main()
{
char* pdata = "{[([]{})[]([])]}";
SqStack Myps; //定义栈管理对象
InitStack(&Myps);
if(OK == CheckKuohu(&Myps,pdata))
{
printf("匹配");
}
else
{
printf("不匹配阿!");
}
return;
}