-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_1_2.c
99 lines (99 loc) · 1.66 KB
/
test_1_2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
typedef char STDateType;
typedef struct stack
{
STDateType* a;
int size;
int capacity;
}stack;
void stackInit(stack* pst)
{
assert(pst);
pst->a = (STDateType*)malloc(sizeof(STDateType)* 4);
pst->size = 0;
pst->capacity = 4;
}
void stackDestory(stack* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->size = pst->capacity = 0;
}
//入栈
void stackPush(stack* pst, STDateType x)
{
assert(pst);
if (pst->size == pst->capacity)
{
pst->capacity *= 2;
STDateType* tmp = (STDateType*)realloc(pst->a, sizeof(STDateType)*pst->capacity);
pst->a = tmp;
}
pst->a[pst->size] = x;
pst->size++;
}
//出栈
void stackPop(stack* pst)
{
assert(pst);
assert(pst->size > 0);
pst->size--;
}
int stackEmpty(stack* pst)//返回1是空,返回0是非空
{
assert(pst);
return pst->size == 0 ? 1 : 0;
}
//获取栈顶的数据
STDateType stackTop(stack* pst)
{
assert(pst);
assert(pst->size > 0);
return pst->a[pst->size - 1];
}
bool isValid(char * s){
stack st;
stackInit(&st);
bool ret;
while (*s != '\0')
{
//是前括号 入栈
if (*s == '[' || *s == '(' || *s == '{')
{
stackPush(&st, *s);
s++;
}
else//后括号与栈顶元素相比较
{
if (stackEmpty(&st)) //如果栈里是空,说明后括号比前括号多
{
ret = false;
break;
}
char top = stackTop(&st);//取栈顶元素
if (*s == ']' && top != '[')
{
ret = false;
break;
}
if (*s == ')' && top != '(')
{
ret = false;
break;
}
if (*s == '}' && top != '{')
{
ret = false;
break;
}
stackPop(&st);//弹出
s++;//继续比
}
}
if (*s == '\0')//说明前括号比后括号少
{
ret = stackEmpty(&st);//判断栈里还有无前括号,有0,没有非0
}
stackDestory(&st);
return ret == 0 ? false : true;
}