栈的概念与结构
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。
进行数据插入和删除操作的一端称为栈顶,另一端称为栈底
栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶
出栈:栈的删除操作叫做出栈。出数据也在栈顶
栈的实现
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优。因为数组在尾上插入数据的代价比较小。
利用结构体和typedef定义一个栈
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capaicty;
}ST;
初始化栈
void STInit(ST* pst)
{
pst->a = NULL;
pst->top = 0;
pst->capaicty = 0;
}
销毁栈
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->top = pst->capaicty = 0;
}
入栈
void STPush(ST* pst, STDataType x)
{
assert(pst);
if (pst->top == pst->capaicty)
{
int newcapaicty = pst->capaicty == 0 ? 3 : 2 * pst->capaicty;
STDataType* tmp = (STDataType*)realloc(pst->a, newcapaicty * sizeof(STDataType));
if (tmp == NULL)
{
return;
}
pst->a = tmp;
pst->capaicty = newcapaicty;
}
pst->a[pst->top] = x;
pst->top++;
}
检查栈是否为空
bool STEmpty(ST* pst)
{
assert(pst);
return pst->top == 0;
}
出栈
void STPop(ST* pst)
{
assert(pst);
assert(!STEmpty(pst));
pst->top--;
}
获取栈顶元素
STDataType STTop(ST* pst)
{
assert(pst);
assert(!STEmpty(pst));
return pst->a[pst->top - 1];
}
获取栈的元素个数
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}
完整代码
Stack.h
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capaicty;
}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);
Stack.c
#include"Stack.h"
void STInit(ST* pst)
{
pst->a = NULL;
pst->top = 0;
pst->capaicty = 0;
}
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->top = pst->capaicty = 0;
}
void STPush(ST* pst, STDataType x)
{
assert(pst);
if (pst->top == pst->capaicty)
{
int newcapaicty = pst->capaicty == 0 ? 3 : 2 * pst->capaicty;
STDataType* tmp = (STDataType*)realloc(pst->a, newcapaicty * sizeof(STDataType));
if (tmp == NULL)
{
return;
}
pst->a = tmp;
pst->capaicty = newcapaicty;
}
pst->a[pst->top] = x;
pst->top++;
}
void STPop(ST* pst)
{
assert(pst);
assert(!STEmpty(pst));
pst->top--;
}
STDataType STTop(ST* pst)
{
assert(pst);
assert(!STEmpty(pst));
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;
}
测试
#include"Stack.h"
int main()
{
ST st;
STInit(&st);
STPush(&st, 1);
STPush(&st, 2);
STPush(&st, 3);
STPush(&st, 4);
printf("栈顶元素:%d\n", STTop(&st));
printf("栈中元素个数:%d\n", STSize(&st));
STPop(&st);
printf("栈顶元素:%d\n", STTop(&st));
STPush(&st, 5);
STPush(&st, 6);
while (!STEmpty(&st))
{
printf("栈顶元素:%d\n", STTop(&st));
STPop(&st);
}
STDestroy(&st);
return 0;
}