栈 括号匹配

#include <cstdio>
#include <stdlib.h>
#define Stack_size 100
typedef char ElemType;
typedef struct Node
{
    ElemType elem[Stack_size];
    int top;
} Seqstack;
void Initstack (Seqstack *s)
{
    s->top=-1;
}
int Push(Seqstack *s, ElemType x)  //将元素x入栈
{
    if(s->top==Stack_size-1) return false;
    s->top++;
    s->elem[s->top]=x;
    return true;
}

int Pop(Seqstack *s, ElemType *x)   //将栈顶元素出栈 通过x带出
{
    if(s->top==-1) return false;
    else{
        *x=s->elem[s->top];
        s->top--;
        return true;
    }
}

int Gettop(Seqstack *s, ElemType *x) //读出栈顶元素 通过x带出
{
    if(s->top==-1) return false;
    else{
        *x=s->elem[s->top];
        return true;
    }
}

int Isempty(Seqstack *s)  //判断栈是否为空 空的话返回1  非空返回0
{
    if(s->top==-1) return true;
    else return false;
}

int IsFull(Seqstack *s ) //判断栈是否满了 满的话返回1  不满返回0
{
    if(s->top==Stack_size-1) return true;
    else return false;
}

int Match(char a,char b)
{
    if(a=='(' && b==')') return 1;
    if(a=='{' && b=='}') return 1;
    if(a=='[' && b==']') return 1;
    return 0;
}
void BracketMatch(char *str )
{
    Seqstack s;char ch;
    Initstack(&s);
    for(int i=0;str[i]!='\0';i++)
    {
        switch(str[i])
        {
        case '(':
        case '[':
        case '{':
            Push(&s,str[i]);
            break;
        case ')':
        case ']':
        case '}':
            if(Isempty(& s)) {
                    printf("匹配不成功\n");
                    return ;
            }
            else{
                Gettop(&s,&ch);
                if(Match(ch,str[i])) Pop(&s,&ch);
                else {
                        printf("匹配不成功\n");
                        return;
                }
            }
        }
    }
    if(Isempty(&s)) printf("匹配成功\n");
    else printf("左括号多余\n");
}
int main()
{
    char str[20];
    printf("请输入要匹配的括号\n");
    scanf("%s",&str);
    BracketMatch(str);
    return 0;
}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值