有效的括號(C語言實現)

有效的括號

給定一個只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判斷字符串是否有效。

C語言中沒有棧容器,所以自己創建了一個棧

typedef struct Node
{
    char s;
    struct Node* next;
}node,*pnode;

typedef struct Stack
{
    pnode ptop;
    pnode pbase;
}stack,*pstack;

stack init_stack()
{
    pnode phead = (pnode)malloc(sizeof(node));
    stack S;
    S.ptop = phead;
    S.pbase = phead;
    phead->next = NULL;
    return S;
}

void destory_stack(pstack ps)
{
    pnode p = ps->ptop;
    while(ps->ptop != ps->pbase)
    {
        p = p->next;
        free(ps->ptop);
        ps->ptop = p;
    }
    free(ps->pbase);
    ps->pbase = ps->ptop = NULL;
    return;
}

void Push(pstack ps,char val)
{
    pnode pnew = (pnode)malloc(sizeof(node));
    pnew ->s = val;
    pnew ->next = ps->ptop;
    ps->ptop = pnew;
    return;
}

char getElem(pstack ps)
{
    char s = ps ->ptop ->s;
    return s;
}

void pop(pstack ps)
{
    pnode p = ps->ptop->next;
    free(ps->ptop);
    ps->ptop = p;
    return;
}

bool isEmpty(pstack ps)
{
    if(ps->ptop == ps->pbase)
        return true;
    else
        return false;
}

bool isValid(char * s){
    stack S = init_stack();
    char* p;
    p = s;
    for(;*p!='\0';p++)
    {
        if(*p == '(' || *p == '[' || *p == '{')
        {
            Push(&S,*p);
        }
        else if(*p==')')
        {
            if(isEmpty(&S))
            {
                destory_stack(&S);
                return false;
            }
            else
            {
                if(getElem(&S) == '(')
                {
                    pop(&S);
                    continue;
                }
                else
                {
                    destory_stack(&S);
                    return false;
                }
            }
        }
        else if(*p==']')
        {
            if(isEmpty(&S))
            {
                destory_stack(&S);
                return false;
            }
            else
            {
                if(getElem(&S) == '[')
                {
                    pop(&S);
                    continue;
                }
                else
                {
                    destory_stack(&S);
                    return false;
                }
            }
        }
        else if(*p=='}')
        {
            if(isEmpty(&S))
            {
                destory_stack(&S);
                return false;
            }
            else
            {
                if(getElem(&S) == '{')
                {
                    pop(&S);
                    continue;
                }
                else
                {
                    destory_stack(&S);
                    return false;
                }
            }
        }
    }
    if(isEmpty(&S))
    {
        destory_stack(&S);
        return true;
    }
    else
    {
        destory_stack(&S);
        return false;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章