头文件
Stack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#define CAPACITY_INIT 4
typedef int STDataType;
typedef struct Stack {
STDataType* a;
int size;
int capacity;
}Stack;
void StackInit(Stack* ps);
void StackPush(Stack* ps, STDataType x);
void StackPop(Stack* ps);
STDataType StackTop(Stack* ps);
int StackSize(Stack* ps);
int StackEmpty(Stack* ps);
void StackDestroy(Stack* ps);
实现文件
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
void StackInit(Stack* ps)
{
assert(ps);
ps->a = (STDataType*)malloc(sizeof(STDataType) * CAPACITY_INIT);
if (ps->a == NULL)
{
perror("malloc fail!");
return;
}
ps->size = 0;
ps->capacity = CAPACITY_INIT;
}
void StackChekCapacity(Stack* ps)
{
assert(ps);
if (ps->size == ps->capacity)
{
ps->a = (STDataType*)realloc(ps->a, sizeof(STDataType) * (ps->capacity) * 2);
if (ps->a == NULL)
{
perror("realloc fail!");
return;
}
ps->capacity *= 2;
}
}
void StackPush(Stack* ps, STDataType x)
{
assert(ps);
StackChekCapacity(ps);
ps->a[ps->size++] = x;
}
void StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->size--;
}
STDataType StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->size - 1];
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->size;
}
int StackEmpty(Stack* ps)
{
assert(ps);
if (ps->size == 0)
return 1;
else
return 0;
}
void StackDestroy(Stack* ps)
{
assert(ps);
ps->size = 0;
ps->capacity = 0;
free(ps->a);
}
测试文件
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
#include<stdbool.h>
经典题目
bool isValid(char* s) {
Stack a;
Stack* ps = &a;
StackInit(ps);
int len = strlen(s);
for (int i = 0; i < len; i++)
{
char tmp = *(s + i);
if (tmp == '(' || tmp == '[' || tmp == '{')
{
StackPush(ps, tmp);
}
else
{
if (StackEmpty(ps))
return false;
char left = StackTop(ps);
if (left == '(')
left = ')';
else if (left == '[')
left = ']';
else
left = '}';
StackPop(ps);
if (left != tmp)
return false;
}
}
if (!StackEmpty(ps))
return false;
StackDestroy(ps);
return true;
}