栈结构概述
栈是一种后进先出(LIFO)的线性数据结构,核心操作包括入栈(Push)和出栈(Pop)。通过栈顶指针动态管理数据存取。
可以将栈理解为羽毛球桶
栈的数组实现设计
核心成员变量
- 数组指针 *arr
- 栈顶位置下标 top
- 栈容量 capacity
边界条件
- 栈空:
top == 0 - 栈满:
top == capacity
基本操作实现
初始化栈
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
检查栈容量
//检查容量
void Stack_check(Stack* ps)
{
assert(ps);
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4: 2 * (ps->capacity);
STDatatype* temp = (STDatatype*)realloc(ps->arr, newcapacity * sizeof(STDatatype));
if (temp == NULL)
{
perror("realloc fail!");
exit(1);
}
else
{
ps->arr = temp;
temp = NULL;
ps->capacity = newcapacity;
return;
}
}
}
入栈(Push)
检查栈满后写入数据并移动栈顶指针:
// 入栈
void StackPush(Stack* ps, STDatatype data)
{
assert(ps);
//判断容量
Stack_check(ps);
ps->arr[ps->top] = data;
ps->top++;
}
出栈(Pop)
删除栈顶元素
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
ps->top--;
return ;
}
扩展功能
获取栈顶元素(Peek)
// 获取栈顶元素
STDatatype StackTop(Stack* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->arr[ps->top-1];
}
获取栈中有效元素个数
// 获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
栈判空
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->top == 0;
}
销毁栈
// 销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->arr);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
动态扩容(上述检查栈容量完成)
通过realloc重新分配更大数组
性能与局限性
时间复杂度
- Push/Pop/Peek:O(1)
空间限制
- 动态分配realloc增加复杂度
完整代码示例
Stack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int STDatatype;
typedef struct Stack
{
STDatatype* arr;
int top;
int capacity;
}Stack;
// 初始化栈
void StackInit(Stack* ps);
// 入栈
void StackPush(Stack* ps, STDatatype data);
// 出栈
void StackPop(Stack* ps);
// 获取栈顶元素
STDatatype StackTop(Stack* ps);
// 获取栈中有效元素个数
int StackSize(Stack* ps);
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps);
// 销毁栈
void StackDestroy(Stack* ps);
Stack.c
#define _CRT_SECURE_NO_WARNINGS
#include "stack.h"
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
//检查容量
void Stack_check(Stack* ps)
{
assert(ps);
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4: 2 * (ps->capacity);
STDatatype* temp = (STDatatype*)realloc(ps->arr, newcapacity * sizeof(STDatatype));
if (temp == NULL)
{
perror("realloc fail!");
exit(1);
}
else
{
ps->arr = temp;
temp = NULL;
ps->capacity = newcapacity;
return;
}
}
}
// 入栈
void StackPush(Stack* ps, STDatatype data)
{
assert(ps);
//判断容量
Stack_check(ps);
ps->arr[ps->top] = data;
ps->top++;
}
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
ps->top--;
return ;
}
// 获取栈顶元素
STDatatype StackTop(Stack* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->arr[ps->top-1];
}
// 获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->top == 0;
}
// 销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->arr);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
9万+

被折叠的 条评论
为什么被折叠?



