首页 > 其他 > 详细

括号匹配的检验

时间:2019-10-26 12:05:57      阅读:82      评论:0      收藏:0      [点我收藏+]

头文件中

#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);
}

 

括号匹配的检验

原文:https://www.cnblogs.com/wwww2/p/11741932.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!