仅供参考:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define STACK_INIT_SIZE 10
#define STACK_GROW_SIZE 5
#define ELEMTYPE char
#define OK 1
#define ERROR 0
typedef struct { /*建立一个栈的首结点*/
ELEMTYPE * base;
ELEMTYPE * top;
int stacksize;
} SpStack;
int InitStack(SpStack *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(SpStack *s) { /*判断栈是否为空*/
if (s->top==s->base) return OK;
else return ERROR;
}
int Push(SpStack *s,ELEMTYPE e) { /*往栈顶插入元素即进栈*/
if (s->top-s->base>=s->stacksize) { /*判断是否栈满*/
s->base=((ELEMTYPE*)realloc(s->base,(s->stacksize+STACK_GROW_SIZE)*sizeof(ELEMTYPE)));
if (!s->base) return ERROR;
s->stacksize+=STACK_GROW_SIZE;
s->top=s->base+s->stacksize;
}
*s->top++=e;
return OK;
}
int Pop(SpStack *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(SpStack *s) {
ELEMTYPE e[STACK_INIT_SIZE*2];
ELEMTYPE e1;
int i;
InitStack(s);
fgets(e,STACK_INIT_SIZE*2,stdin);
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() {
SpStack s;
Count(&s);
free(s.base);
}