• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

c++实现数据结构与算法—-1.14 括号检验匹配问题

c++ 海叔叔 4年前 (2021-12-02) 58次浏览 已收录 0个评论
文章目录[隐藏]

关键词:c++,括号匹配

c++++实现数据结构与算法—-1.14 括号检验匹配问题

//***********************************
//功能:括号检验匹配问题
//日期:2017年10月10日
//作者:Ryan2019
//***********************************
#include <iostream>
using namespace std;
typedef char SElemType;
const int StackInitSize=10;
const int StackInc=5;
struct SStack
{
    SElemType *base,*top;
    int stacksize;
};
bool StackInit (SStack &S);//构造栈
bool Push(SStack &S,SElemType &e);//入栈
bool Pop(SStack &S,SElemType &e);//出栈
bool StackEmpty(SStack &S);//空栈
bool Match(SElemType *a);//括号检验匹配
int main()
{
    SElemType a[]="()(";
    SElemType b[]="())";
    SElemType c[]="()()";
    cout<<"表达式a为:"<<a<<endl; 
    if(Match(a))
    {   cout<<"表达式中的括号匹配!"<<endl;   }
    else
    {   cout<<"表达式中的括号不匹配!"<<endl;}
    cout<<"表达式b为:"<<b<<endl;
    if(Match(b))
    {   cout<<"表达式中的括号匹配!"<<endl;   }
    else
    {   cout<<"表达式中的括号不匹配!"<<endl;}
    cout<<"表达式c为:"<<c<<endl;
    if(Match(c))
    {   cout<<"表达式中的括号匹配!"<<endl;   }
    else
    {   cout<<"表达式中的括号不匹配!"<<endl;}
    return 0;
}
bool StackInit (SStack &S)
{
    S.base=new SElemType[StackInitSize];
    if(!S.base) return false;
    S.top=S.base;
    S.stacksize=StackInc;
    return true;
}
bool StackEmpty(SStack &S)
{
    return S.top==S.base;
}
bool Push(SStack &S,SElemType &e)
{
    SElemType *base;
    if(S.top-S.base==S.stacksize)
    {
        base=(SElemType*)realloc(S.base,(S.stacksize+StackInc)*sizeof(SElemType));
        if(!base) return false;
        S.base=base;
        S.top=S.base+S.stacksize;
        S.stacksize+=StackInc;
    }
    *S.top=e;
    S.top++;
    return true;
}
bool Pop(SStack &S,SElemType &e)
{
    if(S.top==S.base) return false;
    S.top--;
    e=*S.top;
    return true;
}
bool Match(SElemType *a)
{  
    SStack S;
    StackInit(S);
    SElemType e;   
    int i=0;
    while(a[i]!='\0')
    {      
        if(a[i]=='(' ||a[i]=='[' || a[i]=='{' )
        {          
            Push(S,a[i]);
        }
        else if(a[i]==')' ||a[i]==']' || a[i]=='}')
        {
            if(!Pop(S,e))
            {
                return false;
            }
            if(e=='(' && a[i]==')' || e=='[' && a[i]==']'|| e=='{' && a[i]=='}')
            {
                i++;   
                continue;
            }
            else{      
                return false;
            }
        }
        else{      
            i++;
            continue;
        }
        i++;
    }
    return StackEmpty(S);
}
来源搞代码网《c++++实现数据结构与算法—-1.14 括号检验匹配问题》http://www.gaodaima.com/68495.html

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:c++实现数据结构与算法—-1.14 括号检验匹配问题
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址