🕺作者@启明星使
🎃专栏:《数据库》《C语言》
🏇分享一句话:
对的人会站在你的前途里 志同道合的人才看得懂同一片风景
大家一起加油🏄♂️🏄♂️🏄♂️
希望得到大家的支持,如果有帮助希望得到的大家三连~~~
目录
前言
思路
1. 定义结构体
2.初始化
3. 销毁
4. 入栈
2 容量足够:
利用数组的性质将值赋给栈顶
栈顶自增
5. 出栈
6. 栈长
7. 栈空
代码实现
1. 定义结构体
2. 初始化
3. 销毁
4. 入栈
5. 出栈
6. 栈长
7. 栈空
OJ题(简单)
题解
实现栈有很多种方式,在这里我们使用的方法是动态数组实现。
栈的概念及结构
typedef struct Sqstack
{Elemtype* a;int top;int capacity;
}Sq;
void Initstack(Sq*st) {assert(st);st->a = (Elemtype*)malloc(sizeof(Elemtype) * 4);if (st->a == NULL) {printf("malloc fail\n");exit(-1);}st->capacity = 4;st->top = 0;
}
void DestroySt(Sq* st) {assert(st);free(st->a);st->a = NULL;st->top = st->capacity = 0;
}
void InsertSt(Sq* st,Elemtype x) {assert(st);if (st->top == st->capacity) {Elemtype* tem = (Elemtype*)realloc(st->a, st->capacity * 2 * sizeof(Elemtype));if (tem == NULL) {printf("realloc fail\n");exit(-1);}else{st->a = tem;st->capacity *= 2;}}st->a[st->top] = x;st->top++;
}
Elemtype TopSt(Sq* st) {assert(st);assert(st->top > 0);return st->a[st->top -1];
}
void PopSt(Sq* st) {assert(st);assert(st->top > 0);st->top--;
}
int Stsize(Sq* st) {assert(st);return st->top;
}
bool StEmpty(Sq* st) {assert(st);return st->top == 0;
}
有效的括号
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()" 输出:true
示例 2:
输入:s = "()[]{}" 输出:true
示例 3:
输入:s = "(]" 输出:false
提示:
1 <= s.length <= 104
s
仅由括号 '()[]{}'
组成
typedef char Elemtype;
typedef struct Sqstack
{Elemtype* a;int top;int capacity;
}Sq;
void Initstack(Sq*st) {assert(st);st->a = (Elemtype*)malloc(sizeof(Elemtype) * 4);if (st->a == NULL) {printf("malloc fail\n");exit(-1);}st->capacity = 4;st->top = 0;
}
void DestroySt(Sq* st) {assert(st);free(st->a);st->a = NULL;st->top = st->capacity = 0;
}
void InsertSt(Sq* st,Elemtype x) {assert(st);if (st->top == st->capacity) {Elemtype* tem = (Elemtype*)realloc(st->a, st->capacity * 2 * sizeof(Elemtype));if (tem == NULL) {printf("realloc fail\n");exit(-1);}else{st->a = tem;st->capacity *= 2;}}st->a[st->top] = x;st->top++;
}
Elemtype TopSt(Sq* st) {assert(st);assert(st->top > 0);
return st->a[st->top -1];
}
void PopSt(Sq* st) {assert(st);assert(st->top > 0);st->top--;
}
int Stsize(Sq* st) {assert(st);return st->top;
}
bool StEmpty(Sq* st) {assert(st);return st->top == 0;
}
int lengths(char*s){int i=0;while(s[i]!='\0'){i++;}return i;
}
bool isValid(char * s){Sq st;Initstack(&st);while(*s !='\0'){switch(*s){case '{':case '[':case '(':{InsertSt(&st,*s);++s;break;}case '}':case ')':case ']':{if(StEmpty(&st)){DestroySt(&st);return false;}char top=TopSt(&st);PopSt(&st);
if((*s=='}'&&top!='{')||(*s==']'&&top!='[')||(*s==')'&&top!='(')){DestroySt(&st);return false;}else{++s;}break;}default:break;}}
bool ret=StEmpty(&st);DestroySt(&st);return ret;}