//********************
//要先自己实现一个栈Stack
typedef char STDateType;
typedef struct Stack
{
STDateType* a;
int top;//top用来操作栈顶的数据
int capacity;
}Stack;
void StackInit(Stack* pst);
void StackDestroy(Stack* pst);
void StackPush(Stack* pst, STDateType x);
void StackPop(Stack* pst);
STDateType StackTop(Stack* pst);
bool StackEmpty(Stack* pst);
int StackSize(Stack* pst);
void StackInit(Stack* pst)
{
assert(pst);
//初始先开辟一点空间
pst->a = (STDateType*)malloc(sizeof(STDateType) * 4);
pst->capacity = 4;
pst->top = 0;
}
void StackDestroy(Stack* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = 0;
pst->top = 0;
}
void StackPush(Stack* pst, STDateType x)
{
assert(pst);
if (pst->top == pst->capacity)
{
STDateType* tmp = (STDateType*)realloc(pst->a, sizeof(STDateType) * pst->capacity * 2);
if (tmp != NULL)
{
pst->a = tmp;
pst->capacity *= 2;
}
}
pst->a[pst->top] = x;
pst->top += 1;
}
void StackPop(Stack* pst)
{
assert(pst);
assert(!StackEmpty(pst));//断言非空
pst->top--;
}
STDateType StackTop(Stack* pst)//取栈顶的数据
{
assert(pst);
assert(!StackEmpty(pst));
return pst->a[pst->top - 1];
}
bool StackEmpty(Stack* pst)
{
assert(pst);
if (pst->top)
return false;
else
return true;
}
int StackSize(Stack* pst)
{
assert(pst);
return pst->top;
}
//*******************
//栈实现完毕
//遇到左括号入栈,遇到右括号看栈内最近的是不是匹配;
bool isValid(char * s){
Stack st;
StackInit(&st);
while(*s)
{
if((*s == '[') || ( *s == '(') || (*s == '{'))
{
StackPush(&st, *s);
s++;//这个不要忘记了
}
else
{
if(StackEmpty(&st))//这种情况说明只有右括号;
{
StackDestroy(&st);//return之前一定要先释放
return false;
}
char top = StackTop(&st);
if((top == '[' && *s != ']')
|| (top == '(' && *s != ')')
|| (top == '{' && *s != '}') )//不匹配的情况
{
StackDestroy(&st);//return之前一定要先释放
return false;
}
else
{
StackPop(&st);//匹配的情况
s++;//这个不要忘记了
}
}
}
bool ret = StackEmpty(&st);//最后判断栈中还有没有多余的左括号;
StackDestroy(&st);
// if(ret == true)
// return true;
// else
// return false;
return ret;
}