【C语言】用栈实现括号匹配详细代码+注释

用栈实现括号匹配–C语言

#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>
#define MaxSize 10
typedef struct
{
    int data[MaxSize];
    int top;
} Stack,*SqStack ;
Stack *init_stack(SqStack s) //初始化
{
    s=(Stack*)malloc(sizeof(Stack));//分配一个顺序栈空间,首地址放在s中
    s->top=-1;
    printf("初始化完成!\n");
    return s;
}
Stack * push(SqStack s,int x) //入栈
{
    if(s->top==MaxSize-1)
    {
        printf("栈满!!\n");
        return s;
    }
    else
    {
        s->top=s->top+1;
        s->data[s->top]=x;
        return s;
    }
}
int pop(SqStack s,int x)
{
    if(s->top==-1)
    {
        printf("栈空!!\n");
        return NULL;
    }
    else
    {
        x=s->data[s->top];
        s->top=s->top-1;
        printf("出栈成功 取出元素为:%c\n",x);
        return x;
    }

}

int get_top(SqStack s,int x)
{
    if(s->top==-1)
    {
        printf("栈空!!\n");
        return NULL;
    }
    else
    {
        x=s->data[s->top];

        printf("取出成功 取出元素为:%s\n",x);
        return x;
    }

}

bool empty_stack(SqStack s)
{
    if(s->top==-1)
    {
        return true;
    }
    else
    {
        return false;
    }

}

bool check(char str[],int length)
{
    char temp;
    SqStack s;
   s= init_stack(s);
    for(int i=0; i<length; i++)//扫描到为左括号,就入栈
    {
        if(str[i]=='[' || str[i]=='{' || str[i]=='(')
        {
            printf("扫描到左括号%c\n",str[i]);
            s= push(s,str[i]);

        }
        else  //扫描到右括号
        {
            if(empty_stack(s)) //扫描到右括号,但是栈空
            {
                return false;
            }
            else//扫描到右括号,但是栈不为空,判断能不能匹配
            {
               temp= pop(s,temp);
                if(str[i]==')' && temp!='(')
                {
                    return false;
                }
                else if(str[i]=='}' && temp!='{')
                {
                    return false;
                }
                else if(str[i]==']' && temp != '[')
                {
                    return false;
                }
            }

        }


    }

    return empty_stack(s);//最后如果栈为空,则匹配成功,即全部匹配完
}
int main()
{
    char str[10]= {'[','(','(','{','[',']','}',')',')',']'};

    if( check(str,10))
    {
        printf("匹配成功!\n");
    }
    else
    {
        printf("匹配失败!\n");
    }
 
    return 0;
}

运行结果

在这里插入图片描述

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值