目录
首先我们明确栈的概念,什么是栈呢?
栈的概念
栈是一种特殊的线性表,它只允许在固定的一端进行插入和删除元素的操作。进行数据的插入和删除的一端为栈顶,另一端为栈底。栈中的元素遵循先进后出的原则。
压栈:栈的插入操作叫做压栈/进栈/入栈
出栈:栈的删除操作叫做出栈
入数据和出数据都是在栈顶进行操作。
栈的实现
首先我们考虑一个问题:那就是实现的方法:顺序表或链表
两种方式都可以实现栈但是我们选择用顺序表实现
原因:
1.如果用链表,删除数据很麻烦,相当于尾删,因为需要遍历;对比顺序表,顺序表的删除很方便。
2.顺序表和链表的数据存储在内存中,对顺序表或链表的数据进行遍历、访问和修改是cpu进行访问的,但是由于cpu和内存的速度差距太大,所以cpu不能直接访问内存,它需要先访问缓存,如果数据在缓存则为命中,命中则直接访问;反之如果没有命中,它会把内存的数据加载到缓存再进行访问。而这块被加载的数据是连续的,所以对于顺序表命中率很高,而链表很低
有前面的知识储备,这里代码实现就很容易了。
初始化函数
void STInit(ST* ps)
{
assert(ps);
ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
if (ps->a == NULL)
{
perror("malloc fail");
return;
}
ps->capacity = 4;
ps->top = 0;
}
销毁函数
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
插入函数
void STPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * ps->capacity * 2);
if (ps->a == NULL)
{
perror("calloc fail");
return;
}
ps->a = tmp;
ps->capacity *= 2;
}
ps->a[ps->top] = x;
ps->top++;
}
判空函数
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
访问栈顶元素以及栈的大小
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
删除函数
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
完整代码
Stack.h
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDataType;
typedef struct Stack
{
int* a;
int top;
int capacity;
}ST;
void STInit(ST* ps);//初始化
void STPush(ST* ps, STDataType x);//插入
void STPop(ST* ps);//删除
int STSize(ST* ps);//栈的大小
bool STEmpty(ST* ps);//判空
void STDestroy(ST* ps);//销毁
STDataType STTop(ST* ps);//访问栈顶元素
Stack.c
#include"Stack.h"
void STInit(ST* ps)
{
assert(ps);
ps->a = (STDataType*)malloc(sizeof(STDataType) * 4);
if (ps->a == NULL)
{
perror("malloc fail");
return;
}
ps->capacity = 4;
ps->top = 0;
}
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void STPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
STDataType* tmp = (STDataType*)realloc(ps->a,sizeof(STDataType) * ps->capacity * 2);
if (ps->a == NULL)
{
perror("calloc fail");
return;
}
ps->a = tmp;
ps->capacity *= 2;
}
ps->a[ps->top] = x;
ps->top++;
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
Test.c
#include"Stack.h"
int main()
{
ST st;
STInit(&st);
STPush(&st, 1);
STPush(&st, 2);
STPush(&st, 3);
STPush(&st, 4);
STPush(&st, 5);
while (!STEmpty(&st))
{
printf("%d ", STTop(&st));
STPop(&st);
}
STDestroy(&st);
return 0;
}