

typedef char STDataType;
typedef struct Stack
{
STDataType* a; //栈中存储的是整形数据;
int top; //栈顶指针,指向栈顶元素,
int capacity;
}ST;
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0; //ps->top = -1;
ps->capacity = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackPush(ST* ps,STDataType x)//头插Push
{
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(tmp == NULL)
{
printf("realloc fall\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)//头删;
{
assert(ps);
assert(ps->top > 0);//top指向的是下一个,所以,top=0的时候,其实是-1在处,并无数据,等待头插
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool StackEmpty(ST* ps)//空
{
assert(ps);
if(ps->top > 0)
{
return true;
}
else{
return false;
}
//return ps->top == 0; ??
}
void StackInit(ST* ps);
void StackDestroy(ST* ps);
void StackPush(ST* ps,STDataType x);
void StackPop(ST* ps);
STDataType StackTop(ST* ps);
int StackSize(ST* ps);
bool StackEmpty(ST* ps);
bool isValid(char * s){
ST st;
StackInit(&st); //初始化后,记得销毁??
while(*s)
{ //左括号入栈,右括号出栈,
if(*s == '(' ||
*s == '[' || //左括号入栈,右括号出栈
*s == '{' )
{
StackPush(&st,*s);
++s; //????
}
else
{
//遇到右括号了
if(StackEmpty(&st))
{
return false;
}
STDataType top = StackTop(&st);
StackPop(&st);
if( (*s == '}' &&top != '{')
|| (*s == ')' &&top != '(')
|| (*s == ']' &&top != '[') )//收括号
{
StackDestroy(&st);
return false;
}
else
{
++s;
}
}
}
bool ret = StackEmpty(&st);
StackDestroy(&st);
return ret;
}
- 这个题解是个错误的,如何改动呢
- 初始化栈后,为什么要销毁呢
- 在whil语句中的第一个if语句中,s是地址,地址自加可以吗?为何不是*s