题目:
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int top; // 栈顶
int capacity; // 容量
}Stack;
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->a = NULL;//可开可不开
ps->top = 0;//top初始化为0或者-1都可以,只是a[ps->top]的意义有区别,这里top指向栈顶的下一个位置,也可以看做栈里的元素个数
ps->capacity = 0;
}
// 入栈
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->top == ps->capacity)//空间已满
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//容量为0则初始开辟4个空间,如果不为0则2倍扩容
STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * newcapacity);
if (NULL == tmp)//扩容失败的情况
{
perror("realloc fail!");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top++] = data;
}
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
assert(ps->top > 0);//
ps->top--;
}
// 获取栈顶元素
STDataType StackTop(Stack* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top - 1];
}
// 获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
//if (0 == ps->top)
// return 1;
//else
// return 0;
return ps->top == 0;
}
// 销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
//整体思想:左括号入栈,右括号出栈
bool isValid(char* s)
{
//先构造出栈
Stack ST;
StackInit(&ST);
//建立循环遍历字符串
while(*s)
{
if('('==*s||'['==*s||'{'==*s)//检测到左括号则入栈
StackPush(&ST,*s);
else//检测到右括号,匹配则左括号出栈,不匹配直接返回false
{
if(StackEmpty(&ST))//栈为空,没有左括号
{
StackDestroy(&ST);//不销毁会造成内存泄漏
return false;
}
char top = StackTop(&ST);
StackPop(&ST);
if(*s==')'&&top!='('
||*s=='}'&&top!='{'
||*s==']'&&top!='[' )//不匹配则直接返回false
{
StackDestroy(&ST);
return false;
}
}
s++;//切换下一个字符
}
//栈为空则全都匹配上了,不为空则就还有左括号没有匹配上
bool ret = StackEmpty(&ST);
StackDestroy(&ST);
return ret;
}
结果: