008.栈应用括号匹配的检验C实例

#include <stdio.h>
#include <stdlib.h>

#define OK 1
#define OVERFLOW -2
#define ERROR -1
#define TRUE 1
#define FALSE 0

#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef int status;
typedef char elemType;

typedef struct{
    elemType* base;
    elemType* top;
    int stacksize;
}SqStack;

status initStack(SqStack* S)
{
    S->base=(elemType*)malloc(STACK_INIT_SIZE*sizeof(elemType));
    if(!S->base)
        exit(OVERFLOW);
    S->top=S->base;
    S->stacksize=STACK_INIT_SIZE;
    return OK;
}

status push(SqStack* S,elemType e)
{
    if(S->top-S->base >= S->stacksize)
    {
        S->base=(elemType*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(elemType));
        if(!S->base)
            exit(OVERFLOW);
        S->top=S->base+S->stacksize;
        S->stacksize+=STACKINCREMENT;
    }
    *S->top++=e;
    return OK;
}

status pop(SqStack* S,elemType* e)
{
    if(S->base==S->top)
        return ERROR;
    *e=*--S->top;
    return OK;
}

status getTop(SqStack S,elemType* e)
{
    if(S.base==S.top)
        return ERROR;
    *e=*(S.top-1);
}

status stackEmpty(SqStack S)
{
    if(S.base==S.top)
        return TRUE;
    else
        return FALSE;
}

status printSqStack(SqStack S)
{
    elemType* n;
    n=S.base;
    printf("now: ");
    while(n!=S.top)
    {
        printf("%c",*n++);
    }
    printf("\n");
    return OK;
}

status matchBracket()
{
    char C;
    SqStack S;
    char e;

    initStack(&S);
    printf("input the first open bracket:\n");
    scanf("%c",&C);
    if(C=='<' || C=='(' || C=='[' || C=='{')
    {
        push(&S,C);
    }
    else
    {
        printf("Wrong bracket, bye.");
        exit(ERROR);
    }

    while(!stackEmpty(S))
    {
        fflush(stdin);
        printf("input bracket:\n");
        scanf("%c",&C);
        if(C=='<' || C=='(' || C=='[' || C=='{')
        {
            push(&S,C);
            printSqStack(S);
        }
        else if(C=='>' || C==')' || C==']' || C=='}')
        {
            getTop(S,&e);
            if(C-e==2 || C-e==1)
            {
                pop(&S,&e);
                printf("match success: %c%c\n",e,C);
                printSqStack(S);
            }
            else
                printf("Wrong close bracket, try again.\n");
        }
        else
            printf("Not bracket, try again.\n");
    }
}

int main()
{
    matchBracket();
    return 0;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值