括号匹配的检验

头文件中

#include<stdio.h>
#include<stdlib.h>
typedef char Elem;
typedef int status;
#define MAXSIZE 100
#define ERROR 0
#define OK 1

typedef struct{
   Elem data[MAXSIZE];
   int top;
}SqStack;
//初始化
void Initstack(SqStack &S)
{
    if(!S.data) exit(-1);
    S.top = 0;
}
//入栈
status Push(SqStack &S,Elem e)
{
    if(S.top==MAXSIZE)
    {
        printf("栈满了\n");
        return ERROR;
    }
    S.data[S.top++] = e;
    return OK;

}
//出栈
status Pop(SqStack &S)
{
    if(S.top==0) return ERROR;
    S.top--;
}
//获得栈顶元素
status getTop(SqStack S,Elem &e)
{
    if(S.top==0) return ERROR;
    e = S.data[S.top-1];
    return OK;
}
//括号匹配 status Match(SqStack
&S) { printf("---------------输入想要匹配的括号-----------------\n\n"); printf(" 括号范围[]、{}、()\n"); char str[MAXSIZE]; gets(str); printf("\n"); Elem pre = '#';//假如第一个括号是右括号,则与其匹配,当然肯定匹配错误 int i=0; while(str[i]!='\0') { if(str[i]=='{'||str[i]=='['||str[i]=='(') { Push(S,str[i]); i++; continue; } if(getTop(S,pre)) { if((pre=='{'&&str[i]=='}')||(pre=='['&&str[i]==']')||(pre=='('&&str[i]==')')) { Pop(S); i++; }else{ printf("匹配错误\n"); printf("\n"); printf("----------------------end----------------------"); return ERROR; } }else{ printf("栈空了或输入的第一个是左括号\n\n"); printf("----------------------end-------------------------"); return ERROR; } } if(S.top==0){ printf("匹配成功\n"); printf("\n"); printf("-----------------------end-------------------------"); }else{ printf("匹配错误\n"); printf("\n"); printf("------------------------end------------------------"); } }

 主函数

#include"StringMatch.h"
int main()
{
    SqStack S;
    Initstack(S);
    Match(S);
}

猜你喜欢

转载自www.cnblogs.com/wwww2/p/11741932.html