1、栈:stack
只允许在一端进行插入或删除,这一端称为栈顶,另一端为栈底。
2、结构体设计
typedef int ELEM_TYPE;
typedef struct Stack
{
ELEM_TYPE* base;//用于接受malloc来的数组地址
int top;//保存栈顶元素的下标,也是有效元素的个数
int Stacksize;//用来保存栈的最大长度
}Stack,*PStack;
3、头文件
#pragma once
typedef int ELEM_TYPE;
typedef struct Stack
{
ELEM_TYPE* base;//用于接受malloc来的数组地址
int top;//保存栈顶元素的下标,也是有效元素的个数
int Stacksize;//用来保存栈的最大长度
}Stack,*PStack;
//初始化
void Init_Stack(PStack ps);
//入栈
bool Push(PStack ps, ELEM_TYPE val);
//出栈(出栈成功,返回出栈元素的值,不成功的话无所谓)
bool Pop(PStack ps, ELEM_TYPE* rtval);//rtval是输出参数,帮助函数返回其他信息
//获取栈顶元素
bool Top(PStack ps, ELEM_TYPE* rtval);
//获取有效数据个数
int Get_length(PStack ps);
//判空
bool Is_Empty(PStack ps);
//判满
bool Is_Full(PStack ps);
//扩容
void Inc(PStack ps);
//清空
void Clear(PStack ps);
//销毁
void Destory(PStack ps);
//打印
void Print(PStack ps);
4、函数实现
#include"stack(顺序栈).h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#define INIT_SIZE 10
//初始化
void Init_Stack(PStack ps)
{
assert(ps != NULL);
ps->base = (ELEM_TYPE*)malloc(sizeof(ELEM_TYPE) * INIT_SIZE);//给base申请空间
ps->top = 0;
ps->Stacksize = INIT_SIZE;
}
//入栈
bool Push(PStack ps, ELEM_TYPE val)
{
assert(ps != NULL);
//判满 满扩容,不满插入
//入栈
//top++
if (Is_Full(ps))//判满
{
Inc(ps);//扩容
}
ps->base[ps->top] = val;
ps->top++;//ps->base[ps->top++] = val;
return true;
}
//出栈(出栈成功,返回出栈元素的值,不成功的话无所谓)
bool Pop(PStack ps, ELEM_TYPE* rtval)//rtval是输出参数,帮助函数返回其他信息
{
assert(ps != NULL);
if (Is_Empty(ps))//判空
{
return false;
}
*rtval = ps->base[ps->top-1];
ps->top--;//*rtval = ps->base[--ps->top];
return true;
}
//获取栈顶元素
bool Top(PStack ps, ELEM_TYPE* rtval)
{
assert(ps != NULL);
if (Is_Empty(ps))//判空
{
return false;
}
*rtval = ps->base[ps->top - 1];
return true;
}
//获取有效数据个数
int Get_length(PStack ps)
{
assert(ps != NULL);
return ps->top;
}
//判空
bool Is_Empty(PStack ps)
{
assert(ps != NULL);
return ps->top == 0;
}
//判满
bool Is_Full(PStack ps)
{
assert(ps != NULL);
return ps->top == ps->Stacksize;
}
//扩容
void Inc(PStack ps)//malloc relloc calloc
{
assert(ps != NULL);
ps->base = (ELEM_TYPE*)realloc(ps->base, sizeof(ELEM_TYPE) * ps->Stacksize * 2);//realloc三种扩容方式
assert(ps->base != NULL);
ps->Stacksize *= 2;//扩容之后将大小给出
}
//清空
void Clear(PStack ps)
{
assert(ps != NULL);
ps->top = 0;
}
//销毁
void Destory(PStack ps)
{
assert(ps != NULL);
free(ps);
ps = NULL;
return;
}
//打印
void Print(PStack ps)
{
assert(ps != NULL);
for (int i = 0; i <ps->top; i++)
{
printf("%d ", ps->base[i]);
}
printf("\n");
return;
}
int main()
{
Stack x = {};
PStack ps = &x;
Init_Stack(ps);
for (int i = 0; i < 20; i++)
{
Push(ps,i);
}
Print(ps);
int a=0;
int* rtval = &a;
for (int i = 20; i > 0; i--)
{
Pop(ps,rtval);
printf("%d ", a);
}
Print(ps);
}