T1、出栈顺序相关习题
T2、 有效的括号
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps, STDataType x);
void StackPop(ST* ps);
STDataType StackTop(ST* ps);
bool StackEmpty(ST* ps);
int StackSize(ST* ps);
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = (ps->capacity == 0 ? 4 : ps->capacity * 2);
STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapacity);
if (NULL == tmp)
{
printf("realloc fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return (ps->a[ps->top - 1]);
}
bool StackEmpty(ST* ps)
{
assert(ps);
return (ps->top == 0);
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool isValid(char* s)
{
assert(s);
ST st;
StackInit(&st);
while (*s)
{
if ('(' == *s || '[' == *s || '{' == *s)
{
StackPush(&st,*s);
s++;
}
else
{
if (StackEmpty(&st))
{
StackDestory(&st);
return false;
}
STDataType top = StackTop(&st);
StackPop(&st);
if ('('==top && ')'==*s || '['==top && ']'==*s || '{'==top && '}'==*s)
{
s++;
}
else
{
StackDestory(&st);
return false;
}
}
}
bool ret = StackEmpty(&st);
StackDestory(&st);
return ret;
}
int main()
{
char s[] = "{[()]}";
printf("%d\n", isValid(&s));
return 0;
}