//用数组实现栈
typedef char DataType;
typedef struct stack
{DataType* a;//动态数组int top;//栈顶int capacity; //容量
}ST;void STInit(ST*pst);//初始化void STDestroy(ST* pst);//销毁所有空间void STPush(ST* pst, DataType x);//插入数据到栈中void STPop(ST* pst);//数据跳出栈顶DataType SToPop(ST* pst);//访问栈顶元素bool STEmpty(ST* pst);//判空函数int STSize(ST* pst);//记录栈内有多少元素(有多少人)void STInit(ST* pst)//初始化
{assert(pst);pst->a = NULL; pst->capacity = 0;pst->top = 0;
}
void STDestroy(ST* pst)//销毁所有空间
{assert(pst);free(pst->a);pst->a = NULL;pst->capacity = 0;pst->top = 0;
}
void STPush(ST* pst, DataType x)//插入数据到栈中
{assert(pst);if (pst->capacity == pst->top){int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;//是0就给4,不是0就乘2DataType* tmp = (DataType*)realloc(pst->a, sizeof(DataType) * newcapacity);//扩容好的数组地址if (tmp == NULL){perror("realloc fail");return;}pst->a = tmp;pst->capacity = newcapacity;}pst->a[pst->top] = x;//栈顶放入元素pst->top++;}void STPop(ST* pst)//数据跳出栈顶
{assert(pst);assert(!STEmpty(pst));pst->top--;
}DataType SToPop(ST* pst)//访问栈顶元素
{assert(pst);assert(!STEmpty(pst));return pst->a[pst->top - 1];
}bool STEmpty(ST* pst)//判空函数
{assert(pst);return pst->top == 0; //等于0,bool就真了,
}int STSize(ST* pst)//记录栈内有多少元素(有多少人)
{assert(pst);return pst->top;
}bool isValid(char * s){ST kit;STInit(&kit);while(*s){//1. 左括号入栈 '(', '[', '{'//2. 右括号出栈匹配 ')', ']', '}'//3.栈是空那就是匹配成功的,栈不是空就匹配失败"([{ ])"//只要有一对不相等就返回falseif(*s == '(' ||*s == '{' ||*s == '['){STPush(&kit,*s);}else{if(STEmpty(&kit))//防止"[{}])"还在调用SToPop函数访问造成越界访问{return false;}char tmp =SToPop(&kit);STPop(&kit);if(*s == ')' && tmp != '(' || *s =='}'&& tmp != '{' || *s ==']' && tmp != '[' )//只要有一对不相等就返回false{return false;}}++s;} bool yesno = STEmpty(&kit);//栈是空那就是匹配成功的,栈不是空就匹配失败"([{ ])"STDestroy(&kit);return yesno;
}