zoukankan      html  css  js  c++  java
  • 【算法】括号配对与先输入后打印

    括号配对:假设一个数学算式中包括圆括号"()",方括号”[]"和花括号“{}”三种类型,编写一算法判断表达式的括号是否配对。

    参考1题目解析:

    https://blog.csdn.net/tongxinhaonan/article/details/26596959?utm_source=blogxgwz4

    参考2栈讲解,含经典例子和递归汉诺塔:

    https://wenku.baidu.com/view/ab87615382c4bb4cf7ec4afe04a1b0717fd5b3db.html

    #include <stdio.h>
    #include <malloc.h>
    #include <stdlib.h>
    #include "string.h"
    /*宏定义和链栈类型定义*/
    typedef char DataType;
    #include "LinkStack.h"    //包括链栈实现文件
    int Match(DataType e,DataType ch);    //检验括号是否配对函数
    int main()
    {
        LinkStack S;
        char *p;
        DataType e;
        DataType ch[60];
        InitStack(&S);    //初始化链栈
        printf("请输入带括号的表达式");
        gets(ch);
        p=ch;
        while(*p)
        {
            switch(*p)
            {
            case '(':
            case '[':
            case '{':
                PushStack(S,*p++);
                break;
            case ')':
            case ']':
            case '}':
                if (StackEmpty(S))
                {
                    printf("缺少左括号。
    ");
                    return 0;
                }
                else
                {
                    GetTop(S,&e);
                    if (Match(e,*p))
                    {
                        PopStack(S,&e);
                    }
                    else
                    {
                        printf("左括号不配对
    ");
                        return 0;
                    }
                }
            default:    //如果是其他字符,则不处理,直接指向下一个字符
                p++;
            }
        }
        if (StackEmpty(S))
        {
            printf("括号匹配
    ");
            return 1;
        } 
        else
        {
            printf("缺少右括号
    ");
            return 0;
        }
    }
    int Match(DataType e,DataType ch)
    {
        if (e=='('&&ch==')')
        {
            return 1;
        } 
        else if (e=='['&&ch==']')
        {
            return 1;
        } 
        else if (e=='{'&&ch=='}')
        {
            return 1;
        }
        else
        {
            return 0;
        }
     
    }
  • 相关阅读:
    元素绑定与非元素绑定
    窗口之间的交互,windows和自定义的窗口集合
    e.which
    prop()和attr()
    web动画
    $.proxy()和$.makeArray()
    匿名自执行函数报错
    页面适配
    gulp
    伪元素和伪类
  • 原文地址:https://www.cnblogs.com/paprikatree/p/10516369.html
Copyright © 2011-2022 走看看