有效的括号

typedef char STDataType;
typedef struct Stack
{
    STDataType* a;
    int top;
    int capacity;
}ST;


//初始化
void STInit(ST* pst)
{
        assert(pst);
        pst->a = NULL;
        //pst->top = -1;//让top指向我们的栈顶数据
        pst->top = 0;//让top指向栈顶数据的下一个位置
        pst->capacity = 0;
        //
}


//销毁
void STDestroy(ST* pst)
{
assert(pst->a);
free(pst->a);
pst->a = NULL;
pst->top = pst->capacity = 0;//因为这里使用数组来实现的栈,所以这里的top相当于栈顶元素的下一个位置在数组中的下标
}


//入栈
void STPush(ST* pst, STDataType x)
{
assert(pst);
if(pst->top == pst->capacity)
{
    int newcapacity = pst->capacity == 0 ? 4 : pst->capacity*2;
    STDataType* tmp = (STDataType*)realloc(pst->a,newcapacity*sizeof(STDataType));
    if(tmp == NULL)
    {
    perror("realloc fail");
    return;
    }
    pst->capacity = newcapacity;
    pst->a = tmp;
    
}
pst->a[pst->top] = x;
pst->top++;
}


void STPop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
pst->top--;
}


//返回栈顶元素
STDataType STTop(ST* pst)//返回栈顶元素
{
    assert(pst);
    return pst->a[pst->top-1];
    }

//判空
bool STEmpty(ST* pst)
{
    assert(pst);
    return pst->top == 0;
}

//获取数据个数
int STSize(ST* pst)
{
    assert(pst);
    return pst->top;//这里top相当于数组下标
}


bool isValid(char* s) {
    ST st;
    STInit(&st);
    while (*s) {
        if (*s == '(' || *s == '[' || *s == '{') {
            STPush(&st, *s);
        } 
        else
        {
            if (STEmpty(&st)) {
                
                return false;
            }
            char top = STTop(&st);
            STPop(&st);
            if ((top == '(' && *s != ')') || (top == '[' && *s != ']') ||
                (top == '{' && *s != '}')) {
                return false;
            }
        }
        s++;
    }
    // 看左括号和右括号是否相等
    bool ret = STEmpty(&st);
    STDestroy(&st);
    return ret;
}
 

你可能感兴趣的:(数据结构,C语言)