#include <stdio.h>
#define ERROR 0
#define OK 1
#define ElemType char
#define N 10
#define STACK_INIT_SIZE 100
#define STACKINCERMENT 10
typedef int status;
typedef struct
{
ElemType *top;
ElemType *base;
int stackSize;
}sqStack;
/*创建栈*/
status initStack(sqStack *s)
{
s->base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s->base)
return ERROR;
s->top=s->base;
s->stackSize=STACK_INIT_SIZE;
return OK;
}
int Stacklen(sqStack s)
{
return ( s.top - s.base);
}
/*将一个数值放入栈顶*/
status Push(sqStack *s,ElemType e)
{
if( s->top - s->base >= s->stackSize)
{
s->base=(ElemType *)realloc(s->base,(s->stackSize+STACKINCERMENT) * sizeof(ElemType));
if(!s->base)
return ERROR;
s->top=s->base+s->stackSize;
s->stackSize=s->stackSize+STACKINCERMENT;
}
*(s->top)=e;
s->top++;
return OK;
}
/*从栈顶取出一个数*/
status Pop(sqStack *s,ElemType *e)
{
if(s->top == s->base)
return ERROR;
s->top--;
*e=*(s->top);
return OK;
}
ElemType Popelem(sqStack s)
{ s.top--;
return *(s.top);
}
/*------------栈清空---------*/
status ClearStack(sqStack *s)
{
s->top=s->base;
return OK;
}
int main()
{
int i,x,n,j,sum=0,lenth;
ElemType e,p;
sqStack s,q;
initStack(&s);
initStack(&q);
scanf("%c",&e);
while( e != '#')
{
if(e == '(' || e =='[' || e =='{')
Push(&s,e);
scanf("%c",&e);
lenth=Stacklen(s);
if(e == ')' )
{
if(Popelem(s) == '(')
Pop(&s,&p);
else
{
printf("括号不匹配\n");
exit(0);
}
}
if(e == ']' )
{
if(Popelem(s) == '[')
Pop(&s,&p);
else
{
printf("括号不匹配\n");
exit(0);
}
}
if(e == '}' )
{
if(Popelem(s) == '{')
Pop(&s,&p);
else
{
printf("括号不匹配\n");
exit(0);
}
}
}
getchar();
if( s.top == s.base )
printf("括号匹配\n");
else
{
printf("括号不匹配\n");
exit(0);
}
return 0;
}
【数据结构与算法】栈的应用-括号匹配
最新推荐文章于 2020-10-01 16:44:47 发布