数据结构括号匹配问题
程序代码:
#include<stdio.h> #include<malloc.h> #include<string.h> #define STACK_INIT_SIZE 10 #define STACKINCREMENT 5 #define OK 1 #define ERROR 0 typedef char ElemType; typedef struct { /*建立一个栈的首结点*/ ElemType * base; ElemType * top; int stacksize; } SqStack; int 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 StackEmpty(SqStack *s) { /*判断栈是否为空*/ if (s->top==s->base) return OK; else return ERROR; } int Push(SqStack *s,ElemType e) { /*往栈顶插入元素即进栈*/ if (s->top-s->base>=s->stacksize) { /*判断是否栈满*/ s->base=((ElemType*)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(ElemType))); if (!s->base) return ERROR; s->stacksize+=STACKINCREMENT; s->top=s->base+s->stacksize; } *s->top++=e; return OK; } int Pop(SqStack *s,ElemType *e) { /*让栈顶元素依次输出即出栈*/ if (StackEmpty(s)) return ERROR; *e=*(--s->top); return OK; } int Comp(ElemType a,ElemType b) { if ((a=='('&&b!=')') ||(a=='['&&b!=']') ||(a=='{'&&b!='}')) { return ERROR; } else return OK; } int Count(SqStack *s) { //这一小段是什么意思啊 为什么STACK_INIT_SIZE得*2啊,后面又定义e1是干嘛? ElemType e[STACK_INIT_SIZE*2]; ElemType e1; int i; InitStack(s); fgets(e,STACK_INIT_SIZE*2,stdin); fgets这个函数有什么用?这一段也看不懂 if ('\n'==e[strlen(e)-1]) e[strlen(e)-1]=0; printf("%s\n",e); for (i=0;e[i]!='\0';i++) { switch (e[i]) { case '(': case '[': case '{': Push(s,e[i]); break; case ')': case ']': case '}': if (StackEmpty(s)) { printf("%*s↖右括号多余\n",i+1,""); return(ERROR); } else Pop(s,&e1); if (!Comp(e1,e[i])) { printf("%*s↖左右匹配出错\n",i+1,""); return(ERROR); } } } if (!StackEmpty(s)) { printf("%*s↖左括号多余\n",i,""); return(ERROR); } else { printf("匹配正确\n"); return(OK); } } void main() { SqStack s; Count(&s); free(s.base); }