顺序栈 C语言练习

5 篇文章 0 订阅
#include <stdio.h>

#define bool  char
#define true 1
#define false 0

#define stack_size 100

typedef char StackElemType;

typedef struct
{
    StackElemType elem[stack_size];
    int top;
}SeqStack;

void InitStack(SeqStack *S)
{
    S->top=-1;
}

bool Push(SeqStack *S,StackElemType *e)
{
    if(S->top >= stack_size-1)
    {
        printf("满栈");
        return false;
    }
    S->elem[++ S->top]=*e;
    return true;
}

bool Pop(SeqStack *S,StackElemType *e)
{
    if(S->top==-1)
    {
        printf("空栈 error");
        return false;
    }
    *e = S->elem[S->top--];
    return true;
}

bool GetTop(SeqStack *S,StackElemType *e)
{
    if(S->top==-1)
    {
        return false;
    }
    *e=S->elem[S->top];
    return true;
}

bool IsEmpty(SeqStack *S)
{
    /*
    if(S->top==-1)
    {
        return true;
    }
    else
    {
        return false;
    }*/
    return S->top==-1;
}

bool Match(StackElemType *e1,StackElemType *e2)
{
    if(*e1=='(' && *e2==')' || *e1=='[' && *e2==']' || *e1=='{' && *e2=='}')
    {
        return true;
    }
    return false;
}

void BracketMatch(char *str)
{
    SeqStack S;
    InitStack(&S);
    int i;
    char ch;
    for(i=0;str[i]!='\0';++i)
    {
        //printf("%c ",str[i]);
        switch(str[i])
        {
        case '(':
        case '[':
        case '{':
            Push(&S,&str[i]);
            break;
        case ')':
        case ']':
        case '}':
            if(IsEmpty(&S))
            {
                printf("\n右括号多余");
            }
            else
            {
                GetTop(&S,&ch);
                if(Match(&ch,&str[i]))
                {
                    Pop(&S,&ch);
                }
                else
                {
                    printf("\n左右括号不匹配");
                    printf("ch:%c str[i]:%c ",ch,str[i]);
                    return;
                }
            }
        }
    }
    if(IsEmpty(&S))
    {
        printf("括号匹配");
    }
    else
    {
        printf("括号不匹配");
    }
}

int main()
{
    char str1[100];
    scanf("%s",str1);
    /*
    SeqStack S1;
    InitStack(&S1);
    */
    BracketMatch(str1);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值