严蔚敏 吴伟明 数据结构 栈的基本操作实现 括号匹配
#include<stdio.h>#include<malloc.h>
#include<stdlib.h>
#include<string.h>
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
typedef struct {
int *base;
int *top;
int stacksize;
}sqstack;
void initstack(sqstack *s){
s->base=(int *)malloc(sizeof(int)*STACK_INIT_SIZE);
if(!s->base) exit(0);
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
}
int stackempty(sqstack s){
if(s.base==s.top) return 1;
else return 0;
}
void gettop(sqstack s,int *e){
if(s.top==s.base) return;
*e=*(s.top-1);
}
void push(sqstack *s,int e){
if(s->top-s->base>=s->stacksize){
if(!(s->base=(int*)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(int))))
exit(-2);
s->top=s->base+s->stacksize;
s->stacksize+=STACKINCREMENT;
}
*s->top++=e;
}
void pop(sqstack *s,int *e){
if(s->top==s->base) return;
*e=*(--s->top);
}
void check(){
sqstack s;
char *p,ch[20],c;
initstack(&s);
gets(ch);
p=ch;
while(*p){
switch(*p){
case '(':
case '[':
push(&s,*p++);
break;
case ')':
case ']':
if(stackempty(s)){printf("error0\n");exit(0);}
else {pop(&s,&c);
if(*p==')'&&c!='('||*p=='['&&c!=']')
{printf("error1\n");
exit(0);
}
else{
p++;
break;
}
}
default:p++;
}
}
if(stackempty(s))
printf("success\n");
else
printf("failure\n");
}
void main(){
check();
}