1.1 基本概念
1.2实现代码
//stack.h
#pragma once
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
typedef char STyleStack;
typedef struct Stack {
STyleStack* a; //动态开辟空间
int capacity;//记录容量
int top;//栈顶
}ST;
// 初始化栈
void StackInit(ST* ps);
// 入栈
void StackPush(ST* ps, STyleStack x);
// 出栈
void StackPop(ST* ps);
// 获取栈顶元素
STyleStack StackTop(ST* ps);
// 获取栈中有效元素个数
int StackSize(ST* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(ST* ps);
// 销毁栈
void StackDestroy(ST* ps);
//stack.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "stack.h"
// 初始化栈
void StackInit(ST* ps) {
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;//表示栈顶元素下一个
}
//入栈
void StackPush(ST* ps, STyleStack x)
{
if (ps->top == ps->capacity)
{
assert(ps);
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STyleStack* tmp = (STyleStack*)realloc(ps->a, sizeof(STyleStack) * newcapacity);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
// 出栈
void StackPop(ST* ps)
{
assert(ps);
ps->top--;
}
// 获取栈顶元素
STyleStack StackTop(ST* ps)
{
assert(ps->top>0);
return ps->a[ps->top-1];
}
// 获取栈中有效元素个数
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
// 销毁栈
void StackDestroy(ST* ps)
{
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
//test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "stack.h"
int main()
{
ST stack;
StackInit(&stack);
StackPush(&stack, '[');
StackPush(&stack, '+');
StackPush(&stack, '-');
StackPush(&stack, '*');
StackPush(&stack, ')');
while (!StackEmpty(&stack))
{
printf("%c ", StackTop(&stack));
StackPop(&stack);
}
StackDestroy(&stack);
}