栈的含义和理解
栈的含义
指的一种特定形式,以特定的形式进行储存输出,是一种线性表。
栈的规定
只允许在一端进行插入或删除操作的线性表。
就像弹夹一样,一颗一颗像弹夹里面压子弹,在卸下子弹的时候是最后压的子弹先退出来
如图所示 ⬆
顶部被称为栈顶,底部被称为栈底。
栈的实现
栈的种类
我们学过的知识,可以用两种方式进行实现。
1.通过数组来实现
2.通过链表来实现
(1)单链表实现
(2)双链表实现
我们这次用数组实现。
栈的实现方法
定义框架
typedef int STDataType;
typedef struct Stack
{
int * a;
int top;//栈顶的位置
int capacity;
}ST;
定义一个指针,两个整形变量,一个记录栈元素,一个记录栈大小。
初始化函数
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->top = 0;
pst->capacity = 0;
}
销毁函数
void STDestroy(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->capacity = pst->top = 0;
}
入栈函数
void STPush(ST* pst, STDataType x)
{
assert(pst);
if (pst->top == pst->capacity)
{
int newcapcity = pst->capacity == 0 ? 4 : (pst->capacity) * 2;
STDataType tmp = (STDataType*)realloc(pst->a, sizeof(STDataType)*newcapcity);
if (tmp == NULL)
{
perror("fail");
return;
}
pst->a = tmp;
pst->capacity = newcapcity;
}
pst->a[pst->top] = x;
pst->top++;
}
出栈函数
void STPop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
pst->top--;
}
读取栈顶元素函数
STDataType STTop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
return pst->a[(pst->top)-1];
}
判断栈是否为空
bool STEmpty(ST* pst)
{
assert(pst);
return pst->top == 0;
}
查看栈内元素数量
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}
完整实现
.h
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int STDataType;
typedef struct Stack
{
int * a;
int top;//栈顶的位置
int capacity;
}ST;
void STInit(ST* pst);
void STDestroy(ST* pst);
void STPush(ST* pst, STDataType x);
void STPop(ST* pst);
STDataType STTop(ST* pst);
bool STEmpty(ST* pst);
int STSize(ST* pst);
.c
#include "Stack.h"
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->top = 0;
pst->capacity = 0;
}
void STDestroy(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->capacity = pst->top = 0;
}
void STPush(ST* pst, STDataType x)
{
assert(pst);
if (pst->top == pst->capacity)
{
int newcapcity = pst->capacity == 0 ? 4 : (pst->capacity) * 2;
STDataType tmp = (STDataType*)realloc(pst->a, sizeof(STDataType)*newcapcity);
if (tmp == NULL)
{
perror("fail");
return;
}
pst->a = tmp;
pst->capacity = newcapcity;
}
pst->a[pst->top] = x;
pst->top++;
}
void STPop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
pst->top--;
}
STDataType STTop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
return pst->a[(pst->top)-1];
}
bool STEmpty(ST* pst)
{
assert(pst);
return pst->top == 0;
}
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}
调用方法
栈的调用方法有所不同
int main()
{
ST s;
STInit(&s);
STPush(&s, 1);
STPush(&s, 2);
STPush(&s, 3);
STPush(&s, 4);
STPush(&s, 5);
printf("入栈顺序:1 2 3 4 5\n");
printf("出栈顺序:");
while (!STEmpty(&s))
{
printf("%d ", STTop(&s));
STPop(&s);
}
printf("\n");
STDestroy(&s);
return 0;
}