括号匹配的判定----《数据结构》

#include<stdio.h>  
#include<malloc.h>  
#include<stdlib.h>  
#include<string.h> 

typedef struct{
    char *base;
    char *top;
    int stacksize;
}SqStack; 

int InitStack(SqStack &S){
    S.base = (char *)malloc(100*sizeof(char));
    if(!S.base){
        printf("储存空间分配失败");
        exit(-2);
    }
    S.top = S.base;
    S.stacksize = 100;
    return 1;
}

char GetTop(SqStack S){
    if(S.top!=S.base)
 
    return *(S.top-1); 
}
int Push(SqStack &S,char e){
    if(S.top-S.base==S.stacksize){
        return 0; 
    }
    
    *S.top++ = e;
    return 1;
}
int Pop(SqStack &S,char &e){
    if(S.base!=S.top)
    e = *--S.top;
    return 1;
}
int Judge(char e){
    if(e=='('||e==')'||e=='['||e==']')
        return 1;
    return 0;
}

int Judge2(char a,char b){
    if((a=='('&&b==')')||(a=='['&&b==']'))
        return 1;
    return 0;
}

int main(){
    SqStack S;
    char a,c,x,y;
    InitStack(S);
    printf("请输入表达式:"); 
    x = getchar();
    while(Judge(x)){
        printf("1");
        if(x=='('||x=='['){
            Push(S,x);
            x=getchar();
        }else{
            if(!Judge2(GetTop(S),x)){
                printf("不合法");
                exit(0);
            }
            Pop(S,c);
            x = getchar();
            }
        }
        
    printf("合法"); 
    
    return 0;    

    }
    

 

posted @ 2017-11-20 22:06  自由的背包  阅读(444)  评论(0编辑  收藏  举报