头文件:Stack.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* pdata;
int top;
int capacity;
}ST;
extern void StackInit(ST*);
extern void StackDestroy(ST*);
extern void StackPush(ST*, STDataType);
extern void StackPop(ST*);
extern STDataType StackTop(ST*);
extern bool StackEmpty(ST*);
extern int StackSize(ST*);
源文件:Stack.c
#include"Stack.h"
void StackInit(ST* ps)
{
assert(ps);
ps->pdata = NULL;
ps->top = ps->capacity = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->pdata);
ps->pdata = NULL;
ps->top = ps->capacity = 0;
}
void StackPush(ST* ps, STDataType data)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->pdata, newcapacity*sizeof(STDataType));
if(tmp==NULL)
{
perror("realloc fail");
exit(EXIT_FAILURE);
}
ps->pdata = tmp;
ps->capacity = newcapacity;
}
ps->pdata[ps->top] = data;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->pdata[ps->top - 1];
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
C语言实现堆栈数据结构详解
本文档详细介绍了使用C语言编写的堆栈数据结构,包括初始化、销毁、push、pop、获取栈顶元素、判断栈是否为空以及获取栈的大小。通过源代码展示了如何动态扩展栈内存并处理边界情况。
461

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



