数据结构栈应用括号匹配

#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");
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值