括号匹配问题

#include<string.h>
#include <malloc.h>
#include <stdio.h>
#define MaxSize 100  /* 堆栈最大容量   */
#define OK 1
#define ERROR 0
typedef int Status;
typedef char ElemType;
typedef int Position;
typedef struct
{
    ElemType Data[MaxSize];    /* 存储元素的数组 */
    Position top;               /* 栈顶指针, 指示栈顶元素之后的位置 */
} SeqStack;

Status StackEmpty(SeqStack s);
Status Push(SeqStack &L, ElemType e);
Status Pop(SeqStack &L, ElemType &e);
Status GetPop(SeqStack &L,ElemType &e);
int match(SeqStack &L);
int main()
{
    SeqStack L;
    L.top = 0;
    if(match(L))
        printf("匹配成功!\n");
    else
        printf("匹配失败!\n");
    return 0;
}
int match(SeqStack &L)
{
    char str[105];
    printf("请输入括号:\n");
    // getchar();
    scanf("%s",str);
    int len = strlen(str);
    int i;
    //printf("%s\n",str);
    char e = '0';


    for(i=0; i<len; i++)
    {
        if(str[i]=='['||str[i]=='(')
        {
            Push(L,str[i]);
        }
        // GetPop(L,e);
        // printf("%c\n",e);
        else if(str[i] == ')')
        {
            if(GetPop(L,e))
            {
                //printf("%c\n",e);
                if(e == '(')
                {
                    //printf("pipei(\n");
                    Pop(L,e);
                }
                else
                {
                    //printf("2\n");
                    Push(L,str[i]);
                }
            }
            else
                Push(L,str[i]);
        }
        else if(str[i] == ']')
        {
            if(GetPop(L,e))
            {
                if(e == '[')
                {
                    //printf("pipei[\n");
                    Pop(L,e);
                }
                else
                {
                    Push(L,str[i]);
                }
            }
            else
                Push(L,str[i]);
        }
    }

    if(StackEmpty(L))
        return 1;
    else
        return 0;
    /*while(!StackEmpty(L))
    {
        Pop(L, e);
        printf("%c\n", e);
    }*/

    return 0;
}
Status StackEmpty(SeqStack s) //判断栈s是否为空
{
    return s.top == 0;
}
Status GetPop(SeqStack &L,ElemType &e)
{
    if(StackEmpty(L))
        return ERROR;
    else
    {
        e = L.Data[L.top-1];
        //printf("shi%cshi",e);

    }
    return OK;
}

Status Push(SeqStack &L, ElemType e)
{

    L.Data[L.top] = e;
    L.top++;
    return OK;
}

Status Pop(SeqStack &L, ElemType &e)
{
    if(StackEmpty(L))
        return ERROR;
    e = L.Data[--L.top];

    return OK;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值