zoukankan      html  css  js  c++  java
  • 括号匹配问题(顺序栈实现)

    本周老师作业留了两个。先上传一个吧。那个有时间我再传上来~

    本周的要求:

    1.给出顺序栈的存储结构定义。
    2.完成顺序栈的基本操作函数。
    1)      初始化顺序栈
    2)      实现入栈和出栈操作
    3)      实现取栈顶元素和判空操作
    括号匹配问题
    3.编写主函数实现基本操作函数功能,并设置测试数据,测试合法和非法数据的输出结果。
    4.程序调试运行并保存输出结果。
    5.整理并提交实验作业。
    #include <cstdio>
    #include <cstring>
    #define Stack_Size 50
     
    typedef struct 
    {
        char a[Stack_Size];
        int top;
    }SeqStack;
    
    int IsEmpty(SeqStack *S)//栈判空
    {
        return S->top == -1;
    }
    int Match(char ch1,char ch2)//字符串匹配
    {
        switch(ch2){
        case ')':
            if(ch1=='(')
                return 1;
            break;
        case '}':
            if(ch1=='{')
                return 1;
            break;
        case ']':
            if(ch1=='[')
                return 1;
            break;
        }
        return 0;
    } 
    void InitStack(SeqStack * S)//初始化顺序栈
    {
        S->top = -1;
    } 
    void Push(SeqStack * S,char x)//进栈
    {
        S->top++;
        S->a[S->top]=x;
    } 
    void Pop(SeqStack * S,char *x)//出栈
    {
        *x=S->a[S->top];
        S->top--;
    }
    
    void GetTop(SeqStack * S,char *x)
    {
        *x=S->a[S->top]; 
    }
     
    void BracketMatch(char *str)
    {
        SeqStack S;
        char ch;
        InitStack(&S);
        for(int i=0;str[i]!='';i++)
        {
            switch(str[i]){
            case '(':
            case'[':
            case'{':
                Push(&S,str[i]);
                break;
            case ')':
            case']':
            case'}':
                if(IsEmpty(&S)){
                    printf("
    右括号多余!
    ");
                    return ;
                }
                else{
                    GetTop(&S,&ch);
                    if(Match(ch,str[i]))
                        Pop(&S,&ch);
                    else{
                        printf("
     对应的左右括号不同类!
    ");
                        return ;
                    }
                }
    
            }
        }
        if(IsEmpty(&S))
            printf("
    括号匹配!
    ");
        else
            printf("
    左括号多余!
    ");
    }
    
    
    int main()
    {
        char strr[50];
        printf("请输入各种括号
    ");
        gets(strr);
        BracketMatch(strr);
    
        return 0;
    }
    

      

  • 相关阅读:
    Oracle创建表空间、创建用户以及授权、查看权限
    zf2 数据库连接
    ZF2.0用户向导 —— 6. 数据库及模型(Models)
    zf2配置
    zend framework2使用教程【一】安装
    config/application.config.php
    zf2\config\application.config.php
    zf2 数据库album demo
    albumController.php
    登录
  • 原文地址:https://www.cnblogs.com/xzt6/p/5962306.html
Copyright © 2011-2022 走看看