问题描述
实现代码
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST,PST;
void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps,STDataType x);
void StackPop(ST* ps);
STDataType StackTop(ST* ps);
int Stacksize(ST* ps);
bool StackEmpty();
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity*2;
STDataType* tmp = realloc(ps->a,sizeof(STDataType)*newCapacity);
if (NULL == tmp)
{
printf("realloc fail!\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapacity;
}
*(ps->a + ps->top) = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return *(ps->a + ps->top - 1);
}
int Stacksize(ST* ps)
{
assert(ps);
return ps->top;
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0 ;
}
void StackDestory(ST* ps)
{
void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
return;
}
}
bool isValid(char * s){
ST st;
StackInit(&st);
while(*s)
{
if('(' == *s||'[' == *s||'{' == *s)
{
StackPush(&st,*s);
}
else
{
if(StackEmpty(&st))
{
StackDestory(&st);
return false;
}
if(*s ==')' && StackTop(&st) == '('
|| *s ==']' && StackTop(&st) == '['
|| *s =='}' && StackTop(&st) == '{')
{
StackPop(&st);
}
else
{
StackDestory(&st);
return false;
}
}
s++;
}
if(StackEmpty(&st))
{
StackDestory(&st);
return true;
}
else
{
StackDestory(&st);
return false;
}
}