自学内容网 自学内容网

栈是一种数据结构,只允许在固定一端进行插入和删除功能,进行插入和删除的一端叫做栈顶,另一端叫做栈底,遵循后入先出的规则,就像穿烤串和吃烤串一样

其中,插入数据叫做进栈/压栈/入栈,数据插入在栈顶

对数据的删除叫做出栈

栈的实现

一般用链表或者数组来实现栈,但是由于对于数组来实现元素的插入和删除更加方便,所以用数组来实现栈

头文件

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>

typedef int SLdatetype;
typedef struct SLdate
{
SLdatetype* a;
int top;
int capacity;
}SL;
//初始化
void SLinit(SL* s);

//销毁
void SLdestory(SL* s);

//插入元素
void SLpush(SL* s, SLdatetype x);

//删除元素
void SLpop(SL* s);


//头元素
SLdatetype SLtop(SL* s);

//大小
int SLsize(SL* s);


//是否为空
bool SLempty(SL* s);

源文件

#include"Stack.h"

//初始化
void SLinit(SL* s)
{
assert(s);
s->a = NULL;
s->capacity = s->top = 0;
}

//销毁
void SLdestory(SL* s)
{
assert(s);
free(s->a);
s->a = NULL;
s->capacity = s->top = 0;
}

//插入元素
void SLpush(SL* s, SLdatetype x)
{
assert(s);
if (s->capacity == s->top)
{
int newcapacity = s->capacity == 0 ? 4 : 2 * s->capacity;
SLdatetype* ptemp = (SLdatetype*)realloc(s->a, newcapacity * sizeof(SLdatetype));
if (ptemp == NULL)
{
perror("realloc fail");
return;
}
s->a = ptemp;
s->capacity = newcapacity;
}
s->a[s->top++] = x;
}

//删除元素
void SLpop(SL* s)
{
assert(s);
s->top--;
}


//顶层元素
SLdatetype SLtop(SL* s)
{
assert(s);
return s->a[s->top-1];
}

//大小
int SLsize(SL* s)
{
assert(s);
return s->capacity;
}

测试文件

int main()
{
SL sl;
SLinit(&sl);
SLpush(&sl, 1);
SLpush(&sl, 2);
SLpush(&sl, 3);
while (!SLempty(&sl))
{
int top = SLtop(&sl);
printf("%d", top);
SLpop(&sl);
}


SLdestory(&sl);
return 0;
}

运行效果


原文地址:https://blog.csdn.net/lihaolihao111111/article/details/140278570

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!