?
//用數組實現棧
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;
}