zoukankan      html  css  js  c++  java
  • 数据结构之小括号匹配

    //此程序能够判断一系列小括号匹配问题,其中可以加入一些其他字符例如(3+4)—((7-9)
    #include<windows.h>
    #include<stdio.h>
    #define MaxSize 50
    #define DataType char
    const int MAXSIZE = 100;//栈和队列的最大容量
    typedef struct//栈结构体
    {
        DataType elem[MAXSIZE];
        int top;
    }SqStack;
    void InitStack(SqStack &s)//初始化栈
    {
        s.top = 0;
    }
    bool Push(SqStack &s, DataType x)//向栈中加入一个数据元素
    {
        if (s.top == MAXSIZE)//判满
            return false;
        else
        {
            s.elem[s.top++] = x;//top永远在栈顶元素上一个
            return true;
        }
    }
    bool Pop(SqStack &s, DataType &x)//从栈中输出一个数据元素(栈顶),并删除
    {
        if (s.top != 0)
        {
            x = s.elem[--s.top];
            return true;
        }
        else    //判空
        {
            printf("Underflow!
    ");
            return false;
        }
    }
    bool StackEmpty(SqStack s)//判断是否为空栈
    {
        if (s.top == 0)
            return true;
        return false;
    }
    bool GetTop(SqStack s, DataType &x)//获取栈顶元素,不删除
    {
        if(s.top==0)
            return false;
        x = s.elem[s.top - 1];
        return true;
    }
    bool func()
    {
        SqStack mystack;
        InitStack(mystack);
        char c=getchar();
        while(c!='
    ')
        {
            if(c=='(')
                Push(mystack,c);
            else if(c==')')
            {
                
                if(!Pop(mystack,c))//此处也可以在之前不定义bool型的Pop,而此处改用判断是否为空 ,再弹出
                    return false;//一个函数既判断了能否弹出,又实现了弹出
                /*if (StackEmpty(mystack))
                    return false;
                    Pop...
                */        
            }
            c=getchar();
        }
        if (StackEmpty(mystack))
                    return true;
        else
            return false;
    }
    int main()
    {
        
        printf("请输入一系列小括号以用来判匹配:
    ");
        if(func())
            printf("匹配!
    ");
        else
            printf("不匹配!
    ");
        system("pause");
    }

      如果加入中括号和大括号则需要进行更复杂的匹配设定,不过还是基于此。

  • 相关阅读:
    SQLServer ---------- 安装SQLServer后报错解决
    linux --------- linux系统 安装tomcat
    linux -------------- Linux系统安装jdk
    linux ------ 在Vm 安装 centos系统
    linux ----------- 在VM上 的安装 centos
    Objective-C 图片处理
    Objective-C 符号化
    Objective-C
    Objective-C Core Animation深入理解
    C/C++ 内存对齐
  • 原文地址:https://www.cnblogs.com/BetterThanEver_Victor/p/5709974.html
Copyright © 2011-2022 走看看