类C语言--用栈实现括号匹配--算法与数据结构

本程序采用类C语言,,完整准确运行,代码下方附有运行图片,而且可以控制检验次数

代码区

#include<stdio.h>  
#include<stdlib.h>  
#define stacksize 100  
typedef char SElemType;
typedef struct{
          
     
    char elem[stacksize];  
    int top;  
}SqStack;   

enum Status{
          
   ERROR,OK};

Status InitStack (SqStack &S) 
{
          
     
    S.top = -1;  
	return OK;
}  

Status IsEmpty (SqStack &S)
 {
          
     
    if (S.top == -1)  
		return OK;  
    else  
        return ERROR;  
}  

Status Push (SqStack &S,SElemType e) 
{
          
     
    if(S.top == stacksize-1)  
		return ERROR;  
    S.top++;  
    S.elem[S.top] = e;  
    return OK;  
}  

Status GetTop (SqStack &S,SElemType *e) 
{
          
     
    if (S.top == -1)  return ERROR;  
    else 
	{
          
     
        *e=S.elem[S.top];  
        return OK;  
    }  
}  

Status Pop (SqStack &S,char *x) 
{
          
     
    if (S.top == -1)  
		return ERROR;  
    else {
          
     
        *x=S.elem[S.top];  
        S.top--;  
        return OK;  
    }  
}  

Status BracketMatch (char *str)
{
          
     
    SqStack S;
	int i;
	char e;  
    InitStack (S);  
    for (i=0; str[i]!=; i++)
	{
          
     
        switch (str[i]) 
		{
          
     
            case (:  
            case [:  
            case {:  
                Push (S,str[i]);  
                break;  
            case ):  
				GetTop(S,&e);
                if(e!=()
            break;
				else
					Pop(S,&e);break;
			case ]:  
				GetTop(S,&e);
                if(e!=[)
            break;
				else
					Pop(S,&e);break;

            case }:
				GetTop(S,&e);
                if(e!={)
            break;
				else
					Pop(S,&e);break;
			}
    }  
   if(IsEmpty (S) )  
        printf("匹配
");  
    else  
        printf("未匹配
");  
    return OK;  
	
	return OK;
}  

int main()
{
          
     
    int n;  
    char a[100];  
    scanf("%d",&n);  
    while (n--)
	{
          
     
        scanf("%s",a);  
        BracketMatch (a);  
    }  
    return 0;  
}
经验分享 程序员 微信小程序 职场和发展