用c语言用栈编程的括号匹配问题

#include
#include


#define  Stack_init_size   10
#define  Stackmaxsize   5


#define   status  char
#define   SElemType   char
 
#define  Ok   1
#define  Error   0
  
typedef  struct 
{    /*建立一个栈的首结点*/
SElemType  * base;
SElemType  * top;
int     stacksize;
}Spstack;


status   Initstack(Spstack *s)
{     /*建立空的栈并返回首地址*/
     s->base=((SElemType*)malloc(Stack_init_size*sizeof(SElemType)));
if(!s->base)
return  Error;
s->top=s->base;
s->stacksize=Stack_init_size;
return  Ok;
}


status  Stackempty(Spstack *s)
{    /*判断栈是否为空*/
if(s->top==s->base)
return  Ok;
else  
return  Error;
}


status  Push(Spstack *s,SElemType  e)
{     /*往栈顶插入元素即进栈*/
if(s->top-s->base>=s->stacksize)
{   /*判断是否栈满*/
s->base=((SElemType*)realloc(s->base,(s->stacksize+Stackmaxsize)*sizeof(SElemType)));
  if(!s->base)
   return  Error;
  s->top=s->base+s->stacksize;
  s->stacksize+=Stackmaxsize;
}
*s->top++=e;
return  Ok;
}
  
status  Pop(Spstack *s,SElemType  *e)
{    /*让栈顶元素依次输出即出栈*/
if(Stackempty(s))
return  Error;
*e=*--s->top;
return  Ok;
}


status  Count(Spstack *s,char  e)
{
Initstack(s);
while((e=getchar())!='\n')
{
switch(e)
{     /*输入得左括号*/
case  '(':
case  '[':
case  '{':
{
Push(s,e);
break;
}
case  ')':
{
if(*--s->top=='('&&(*s->top)!=0)
{
Pop(s,&e);
}
else
printf("右括号多余\n");

break;
}
case  ']':
{
if(*--s->top=='['&&(*s->top)!=0)
{

Pop(s,&e);
}
else
printf("右括号多余\n");

break;
}


case  '}':
{
if(*--s->top=='{'&&(*s->top)!=0)
{

Pop(s,&e);
}
else
printf("右括号多余\n");
break;
}
}
}
if(*s->base==*s->top)
{
printf("括号完全匹配\n");
}

    if(*s->top>0)
    printf("左括号多余\n");
return  Ok;


}






int  main()
{
char e;
Spstack  s;
printf("输入你要输入的括号\n");
Count(&s,e);
return  0;
 }

你可能感兴趣的:(栈)