三个括号匹配

算法:假设表达式中包含两种括号:圆括号、方括号和大扩号。检验括号是否匹配可以用堆栈来实现当遇到 ( 或 [或{ 时进栈,遇到 ] 或 ] 或}时出栈进行匹配检验,如果出现不匹配的情况立即结束,否则继续取下一个字符。如果没有遇到不匹配的情况,最后判断栈是否为空,栈为空,括号匹配,否则不匹配

 

源代码:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define NULL 0
typedef int Status;

#define STACK_INIT_SIZE  100
#define STACKINCREMENT   10
typedef char  SElemType;
typedef struct{
     SElemType *base;    //栈底指针
     SElemType *top;     //栈顶指针
     int   stacksize;    //栈容量
 }SqStack;

Status InitStack(SqStack &S){
//构造空栈S 
	S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
	if(!S.base)exit(OVERFLOW);    //存储分配失败
	S.top=S.base;   //空栈
	S.stacksize=STACKINCREMENT;
	return(OK);
}//InitStack


Status Push(SqStack &S, SElemType e){
//插入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.top重新指向栈顶,因realloc
     S.stacksize+=STACK_INIT_SIZE;
   }
   *S.top++=e;    //top指向待插入位置    
   return(OK);
}//Push

Status Pop(SqStack &S,SElemType &e){
    //若栈不空则栈顶元素出栈并用e带回其值
    if(S.top==S.base)return ERROR;
    e=*(--S.top);     //栈顶元素为*(S.top-1)
     return OK;
}

Status StackEmpty(SqStack S){
    
    if(S.top==S.base)return OK;
	return ERROR;
}//StackEmpty

Status match(char *str ) {
	SqStack S;
	InitStack(S);
	int i,	count;
	char e,c;
	i=0;
	count=0;
	while(c=str[i++]&&count==0){
		switch(c){
		case '(':
		case '[':
		case '{':
           Push(S,c);break;
       case '}':
           if(StackEmpty(S))
                    {count++;break;}
            else{
                 Pop(S,e);
                 if(e!='{')
				{count++;break;}}
	   case ']':
           if(StackEmpty(S))
                    {count++;break;}
            else{
                Pop(S,e);
                 if(e!='[')
				 {count++;break;}}
	   case ')':
           if(StackEmpty(S))
                    {count++;break;}
            else{
                 Pop(S,e);
                 if(e!='(')
				 {count++;break;}}
	   default :break;
       }//switch
		if(count==0&&StackEmpty(S))
			printf("The string is match!\n");
		else printf("The string is not match!\n");
		return OK;
	}
}

void  main() { 
	char str[100];
	int count;
	SqStack S;
	InitStack(S);
	printf ("Please input the string:");
	scanf ("%s",str);
	match(str);
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值