C-like language-using stack to achieve bracket matching-algorithm and data structure

This program uses C-like language, which runs completely and accurately. The running picture is attached below the code, and the number of inspections can be controlled.

Code area

#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]!='\0'; 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("匹配\n");  
    else  
        printf("未匹配\n");  
    return OK;  
	
	return OK;
}  

int main()
{  
    int n;  
    char a[100];  
    scanf("%d",&n);  
    while (n--)
	{  
        scanf("%s",a);  
        BracketMatch (a);  
    }  
    return 0;  
}  

Insert picture description here

Published 57 original articles · Liked 54 · Visits 2347

Guess you like

Origin blog.csdn.net/September_C/article/details/105083915