栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端
称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
这里介绍栈的基本操作,具体概念可以网上的概念,直接上代码。
Stack.h
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
//栈:只允许固定一端进行插入和删除元素操作,称为栈顶,另一端为栈底
//出入数据都在栈顶
//我们选择动态数组的话实现起来比较简单
//出数据->尾删 ps->size--
//进数据->尾插 ps->a[ps->size]
//特点:先进后出
#include<stdio.h>
#include<assert.h>
#include<Windows.h>
#include<malloc.h>
#include<stdbool.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* arr; //指向动态开辟的数组
int top; //标志栈顶
int capacity;//容量
}ST;
//初始化
void StackInit(ST* ps);
//入栈
void StackPush(ST* ps, STDataType x);
//出栈
void StackPop(ST* ps);
//返回栈顶元素
STDataType StackType(ST* ps);
//求栈元素个数
int StackSize(ST* ps);
//判断栈是否为空
bool StackEmpty(ST* ps);
//销毁
void StackDestory(ST* ps);
Stack.c
#include "Stack.h"
void StackInit(ST* ps)
{
assert(ps);
STDataType* tmp = (STDataType*)malloc(sizeof(STDataType)* 4); //先给4个空间
if (tmp == NULL)
{
printf("malloc fail\n");
exit(-1);
}
else
{
ps->arr = tmp;
ps->top = 0;
ps->capacity = 4;
}
}
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
STDataType* tmp = (STDataType*)realloc(ps->arr, sizeof(STDataType)*2*ps->capacity);
if (tmp == NULL)
{
printf("realloc fail\n");
exit(-1);
}
else
{
ps->arr = tmp;
ps->capacity *= 2;
}
}
ps->arr[ps->top] = x;
ps->top++;
}
//出栈
void StackPop(ST* ps)
{
assert(ps);
ps->top--;
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0; //最初定义top为0 若top仍未0,说明栈为空
}
//返回栈顶元素
STDataType StackType(ST* ps)
{
assert(ps);
assert(ps->top>0);
return ps->arr[ps->top - 1];
}
//求栈元素个数
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
void StackDestory(ST* ps)
{
assert(ps);
free(ps->arr);
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include"Stack.h"
int main()
{
ST p;
StackInit(&p);
StackPush(&p, 1);
StackPush(&p, 2);
StackPush(&p, 3);
StackPop(&p);
StackPush(&p, 4);
StackPush(&p, 5);
StackPop(&p);
while (!StackEmpty(&p)) //当栈为空,StackEmpty为真 !StackEmpty为假,不进入循环
{
//取栈顶元素
printf("%d ", StackType(&p));
//出栈
StackPop(&p);
}
return 0;
}