用栈实现括号匹配的检验 修改(2008-11-14 19:06:31) 标签:c 语言编程 turbo c2.0 环境实现 栈 括号匹配 it 分类:C 语言编程例子数据结构C语言版 括号匹配问题是编译程序时经常遇到的问题,用以检测语法是否有错。 本文前些天写的用栈实现括号匹配的检验的代码中,其中用了更少变量的代码二有些错误,使得结果总是match,经过修改,现将正确的代码写出,如下 #include #include #define OVERFLOW -1 #define OK 1 #define ERROR 0 #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 #define NULL 0 typedef char SElemType; typedef int Status; typedef struct { SElemType *base; SElemType *top; int stacksize; }SqStack; Status InitStack(SqStack *S) { (*S).base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(!(*S).base) exit(OVERFLOW); (*S).top=(*S).base; (*S).stacksize=STACK_INIT_SIZE; return OK; } Status DestroyStack(SqStack *S) { free((*S).base); (*S).base=NULL; (*S).top=NULL; (*S).stacksize=0; return OK; } Status StackEmpty(SqStack *S) { if((*S).top==(*S).base) return OK; else return ERROR; } Status Push(SqStack *S,SElemType e) { if((*S).top-(*S).base>=(*S).stacksize) {(*S).base=(SElemType *)realloc((*S).base, ((*S).stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!(*S).base) exit(OVERFLOW); (*S).top=(*S).base+(*S).stacksize; (*S).stacksize+=STACKINCREMENT; } *S->top++=e; return OK; } Status Pop(SqStack *S,SElemType *e) { if((*S).top==(*S).base) return ERROR; *e=*--S->top; return OK; } main() { SqStack S; SElemType elem; char e,a[20]; int i=0; int flag=1; clrscr(); if( InitStack(&S))printf("kongjian yijing zhunbei hao!\n"); else printf("there is not enough room!\n"); printf("input the kuohao (<=20 ge) and press '#' to show the end:\n"); do{ scanf("%c",&e); a[i]=e; i++; }while(e!='#'); i=0;e=a[i]; while(e!='#'&&flag) { switch(e) {case '(': Push(&S,e); break; case '[': Push(&S,e);break; case '{': Pus...