括号匹配问题

#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;

}

猜你喜欢

转载自blog.csdn.net/lvhaoye/article/details/80064362
今日推荐