您的位置:首页 > 理论基础 > 数据结构算法

数据结构栈应用括号匹配

2012-11-18 14:57 447 查看
#include<stdio.h>
#include<malloc.h>
#include"stdlib.h"
#define  stack_init_size   100
#define  stackincrement    10
#define  ok                1
#define  error             0
#define  overflow          -1
typedef  int status;
typedef  char selemtype;
/*----------------------struct----------------------*/
typedef struct{
selemtype *base;
selemtype *top;
int stacksize;
}sqstack;
/*-----------------------init-----------------------*/
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;
}
/*-----------------------push-----------------------*/
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;
}
/*-----------------------pop------------------------*/
status pop(sqstack *s,selemtype *e){
if(s->top==s->base)return error;
*e=*--s->top;
return ok;
}
/****************kuohaopipei************************/
void kuohaopipei(){
sqstack sa;
char a,b;
if(initstack(&sa)==ok)printf("Init is ok.\n");
else{
printf("Init is wrong.\n");
exit(0);
}
while((a=getchar())!='#'){
if (a=='('||a=='<'||a=='{'||a=='['){
push(&sa,a);
a=getchar();
continue;
}
else{
if(sa.top-sa.base==0){
printf("右括号多余。\n");
exit(0);
}
else{
pop(&sa,&b);
switch(b){
case '(':if(a==')'){break;}else{printf("括号不匹配\n"); exit(0);}
case '[':if(a==']'){break;}else{printf("括号不匹配\n"); exit(0);}
case '{':if(a=='}'){break;}else{printf("括号不匹配\n"); exit(0);}
default:exit(0);
}
a=getchar();
continue;
}
}
}
if(sa.top-sa.base==0)printf("本次匹配正确。\n");
else printf("左括号多余。\n");
}
void main(){
kuohaopipei();
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: