zoukankan      html  css  js  c++  java
  • 栈的应用——括号匹配

    描述:

    假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序任意,即([]())或[([][])]等都为正确的格式,而[(])为不正确的格式。利用栈编程序检验表达式中的括号是否合法。

    思路:

    1,先实现栈的基本操作:初始化,入栈,出栈等。

    2,每读入一个括号,若是右括号,则或者是置于栈顶的左括号得以消解,或者是不合法的情况;若是左括号,则直接入栈。

    细节:遇左括号则进栈,遇右括号,出栈与之匹配消解。

    #include <stdio.h>
    #include <string.h>
    
    #define MaxSize 100
    typedef char DataType;
    
    typedef struct{
        DataType data[MaxSize];
        int top;
    }Stack;
    
    void InitStack(Stack *S) 
    {  
        S->top=-1;
    } 
    void Push(Stack *S,DataType x)
    {
        if(S->top==MaxSize-1)
            printf("
    栈满,无法压栈!
    "); 
        S->top++;
        S->data[S->top]=x; 
    }
    int EmptyStack(Stack *S)
    { 
        if(S->top== -1)
            return 1;
        else 
            return 0;
    }
    void Pop(Stack *S,DataType *x)     
    {
        if(EmptyStack(S))  
            printf("
     栈空,无法出栈!"); 
        *x=S->data[S->top];  
        S->top--;
    }
    
    void main()
    {
        char str[100]="{}[()]";
        int flag=1;
        Stack S;
        DataType e;
        InitStack(&S);
        //scanf("%s",s);
        for(int i=0;i< strlen(str);i++)
        {
            if ( str[i]=='(' || str[i]=='[' || str[i]=='{')
                Push(&S,str[i]);  
            if (str[i]==')' || str[i]==']' || str[i]=='}')
            {    //有一类情况:[[]]]),栈也为空,所以不能直接不空即出栈
                if (EmptyStack(&S))  
                {
                    flag=0;
                    break;
                }
                else 
                {  
                    Pop(&S,&e);    //出栈顶元素,与刚输入的匹配
                    if ( str[i]==')' && e!='('  ||  str[i]==']' && e!='['  ||  str[i]=='}' && e!='{' )
                    {
                        flag=0;
                        break;
                    }
                }
            }
        }
        if (flag==1 && EmptyStack(&S))
            printf("表达式中的括号合法!
    ");
        else
            printf("不合法!
    ");
    }

     结果:

  • 相关阅读:
    不规范的json文档 转化成 java 对象的处理
    财经接口
    Back-off pulling image "registry.access.redhat.com/rhel7/pod-infrastructure:latest
    VMware Workstation 14 Pro永久激活密钥
    Angular2入门:TypeScript的装饰器
    Angular2入门:TypeScript的模块
    Angular2入门:TypeScript的类
    51nod“省选”模测第二场 B 异或约数和(数论分块)
    51nod1238 最小公倍数之和 V3(莫比乌斯反演)
    cf1139D. Steps to One(dp)
  • 原文地址:https://www.cnblogs.com/lisen10/p/10835057.html
Copyright © 2011-2022 走看看