【数据结构】栈的应用-括号匹配

 括号匹配:

核心代码:

bool BracketsCheck(char str[]){
    LinkList St;
    char *p=str;
    char e;
    InitStack(St);
    while(*p!='\0'){
        //printf("%c\n",*p);
        if(*p=='{'||*p=='['||*p=='('){
            Push(St,*p);
        }else if (*p=='}'||*p==']'||*p==')'){
            if(StackEmpty(St)){
                return false;
            }
            Pop(St,e);
            if((e!='('&&*p==')')||(e!='['&&*p==']')||(e!='{'&&*p=='}')){
                return false;
            }
        }
        p++;
    }
    return StackEmpty(St)?true:false;
}

完整的调试代码:

#include<time.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SElemType char
using namespace std;
typedef struct LNode{
    int data;
    struct LNode *next;
    LNode (int Data=0,struct LNode * Next=NULL){
        data=Data;
        next=Next;
    }
}LNode ,*LinkList ;
void InitStack(LinkList &LS){
    LS=NULL;
}
bool StackEmpty(LinkList LS){
    return LS?false:true;
}
int StackLength(LinkList Ls){
    int cnt=0;
    LinkList p=Ls;
    while(p){
        cnt++;p=p->next;
    }
    return cnt;
}
void Push(LinkList &LS,SElemType e){
    LinkList s;
    s=new LNode(e,LS);
    LS=s;
}
void Pop(LinkList &LS,SElemType &e){
    if(!LS){
        printf("error !!! Stack is empty !\n");
        return ;
    }
    e=LS->data;
    LinkList s=LS;
    LS=LS->next;
    delete s;
}
void GetTop(LinkList LS,SElemType &e){
    if(!LS){
        printf("error !!! Stack is empty !\n");
        return ;
    }
    e=LS->data;
}
bool BracketsCheck(char str[]){
    LinkList St;
    char *p=str;
    char e;
    InitStack(St);
    while(*p!='\0'){
        //printf("%c\n",*p);
        if(*p=='{'||*p=='['||*p=='('){
            Push(St,*p);
        }else if (*p=='}'||*p==']'||*p==')'){
            if(StackEmpty(St)){
                return false;
            }
            Pop(St,e);
            if((e!='('&&*p==')')||(e!='['&&*p==']')||(e!='{'&&*p=='}')){
                return false;
            }
        }
        p++;
    }
    return StackEmpty(St)?true:false;
}
char Brackets[]={"[]{}()"};
int main()
{
    srand(time(0));
    int t=rand();
    int Len=t%100+1;
    char str[100]={'\0'};
    for(int i=0;i<Len;i++){
        t=rand()%6;
        str[i]=Brackets[t];
    }

    printf("%s\n",str);
    puts(BracketsCheck(str)?"Yes":"No");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Z_sea/article/details/85124217