线性栈(通过数组实现)
** 栈模型**
C代码实现
** 代码注释非常详细,可直接编译运行**
//
// Created by wen on 2021/9/20.
//
#define MAX_SIZE 1024
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
// stack struct
typedef struct SStack{
void * data[MAX_SIZE];
int S_size;
}SStack;
//保护数据的安全,避免用户直接操作栈
typedef void * SeqStack ;
//初始化栈
SeqStack init_SeqStack(){
SStack * myStack = malloc(sizeof (SStack));
//判断栈是否为空
if(myStack ==NULL){
return NULL;
}
//设置容量。初始化大小
myStack->S_size = 0;
//初始数组
//里面数组置0
memset(myStack->data,0,sizeof (void *)*MAX_SIZE);
return myStack;
}
//入栈
//入栈的本质是数组的尾插
void Push_SeqStack(SeqStack Stack ,void* data){
//判断数据有效性
if(Stack == NULL)
{
return;
}
if(data == NULL)
{
return;
}
//还原栈
SStack * myStack = Stack;
//判断栈是否变满
if(myStack->S_size >= 1024)
{
return;
}
//尾插
myStack->data[myStack->S_size]=data;
//更新大小
myStack->S_size ++;
}
//出栈,返回出栈的元素
void* Pop_SeqStack(SeqStack * Stack)
{
//出栈的本质是尾删
if(Stack ==NULL)
{
return NULL;
}
//还原栈的真实结构体
SStack *myStack = Stack;
//判断是否为空栈
if(myStack->S_size == 0)
{
return NULL;
}
//* tmp_data为出栈的元素
void * tmp_data = myStack->data[myStack->S_size-1];
//尾部元素置位空
myStack->data[myStack->S_size-1]==NULL;
//栈元素减去1
myStack->S_size --;
//返回出栈的元素
return tmp_data;
}
//返回栈顶
void * Top_SeqStack(SeqStack Stack){
if(Stack == NULL)
{
return NULL;
}
//还原栈结构体
SStack * myStack = Stack;
//如果栈为空栈,返回值为NULL。
if(myStack->S_size == 0){
return NULL;
}
//不为空栈则返回元素
return myStack->data[myStack->S_size-1];
}
//返回栈的大小
int Size_SeqStack(SeqStack Stack){
//还原栈
SStack * myStack =Stack;
//其他情况照常返回
return myStack->S_size;
}
//判断栈是否为空
int isEmpty_SeqStack(SeqStack Stack){
if(Stack ==NULL){
return -1;
//空栈清况1
}
SStack * myStack =Stack;
if(myStack->S_size == 0){
return 1;
//空栈清况2
}
//其他情况不为空
return 0;
}
//销毁栈
void destroy_SeqStack(SeqStack Stack){
if(Stack == NULL)
{
return;
}
//释放堆
free(Stack);
printf("destroy success!\n");
}
/*---------------------------------------------------------*/
//测试
typedef struct Person{
char name[64];
int age;
}Person;
//测试接口
void test2(){
//测试数据
Person P1 ={"tom1",1};
Person P2 ={"tom2",2};
Person P3 ={"tom3",3};
Person P4 ={"tom4",4};
Person P5 ={"tom5",5};
Person P6 ={"tom6",6};
Person P7 ={"tom7",7};
Person P8 ={"tom8",8};
Person P9 ={"tom9",9};
Person P10 ={"tom10",10};
Person a[10]={P1,P2,P3,P4,P5,P6,P7,P8,P9,P10};
//初始化栈
SeqStack * myStack = init_SeqStack();
for (int i = 0; i <10 ; ++i) {
Push_SeqStack(myStack,a+i);
}
int Stack_size = Size_SeqStack(myStack);
printf("Stack size :%d\n",Stack_size);
printf("Stack include element: \n");
//查看栈的元素
//站不为空继续出栈
while (isEmpty_SeqStack(myStack)==0){
Person * p = Top_SeqStack(myStack);
printf("name:%s,age:%d\n",p->name,p->age);
//出栈
Pop_SeqStack(myStack);
}
//出栈完之后的元素个数
printf("After stack size :%d\n",Size_SeqStack(myStack));
//销毁
destroy_SeqStack(myStack);
}
int main(){
test2();
return 0;
}