栈和队列都是我们要熟练掌握的数据结构,他们再生活场景中有着广泛的应用。
栈
1.栈的定义
栈是一种特殊的线性表,其只允许在固定的一段进行删除和插入元素的操作。进行数据插入和删除的另一端成为栈底。插入数据的操作叫入栈,入数据在栈顶。删除数据的操作叫出栈,出数据也在栈顶。后进先出。这个规则就好像是一个羽毛球筒,或者是弹匣。
是不是很形象?
2.栈的实现
栈的实现我们一般用数组或者链表实现,但是相对来说数组会好一些,因为他的缓冲利用率高一些,而且数组比较麻烦。其实动手起来也是很容易的。
3.实现栈的接口
// 初始化栈
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);
这是我们要实现栈需要的接口。
准备工作:
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
4.代码实现
1.初始化栈:
//初始化
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->capacity = 0;
pst->top = 0;
}
2.入栈:
先断言,不能传个空指针。然后判断空间有没有,如果没有就开辟空间,然后把值和next都弄好。
void STPush(ST* pst, STDataType x)
{
assert(pst);
if (pst->top == pst->capacity)
{
int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
STDataType * tmp =(STDataType*) realloc(pst->a, newcapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail!");
return;
}
pst->a = tmp;
pst->capacity = newcapacity;
}
pst->a[pst->top] = x;
pst->top++;
}
3.出栈;
这个很简单,这届把这个数组的数据个数减少一个就可以达到目的。
void STPop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
pst->top--;
}
4.获取栈顶元素:
这个也很简单,我们直接返回栈顶数据就可以了。
//取栈顶的数据
STDataType STTop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
return pst->a[pst->top - 1];
}
5.检测栈是否为空:
直接返回一个关系式,如果为真,那就返回真,如果为假,那就返回假。
//判空
bool STEmpty(ST* pst)
{
assert(pst);
return pst->top == 0;
}
6.获取数据个数:
这个也是我们结构体里面包括了的,所以直接返回好了。
//获取栈数据个数
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}
7.销毁:
就是将我们申请的释放掉好了。
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = 0;
pst->top = 0;
}
总结
其实实现栈还是很简单的,只要前面的顺序表学的扎实,这个实现起来更加简单。