//栈的顺序存储 利用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素
//数组区模拟栈的顺序存储
//注明:C++栈是无法遍历的,所以也不提供打印了
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1024
#define SEQSTACK_TRUE 1
#define SEQSTACK_FALSE 0
typedef struct SEQSTACK{
void* data[MAX_SIZE];
int size;
}SeqStack;
//初始化
SeqStack* Init_SeqStack(){
SeqStack* stack = (SeqStack*)malloc(sizeof(SeqStack));
for(int i=0; i<MAX_SIZE; i++) { //对数组里面的数据进行初始化
stack->data[i] = NULL;
}
stack->size = 0;
return stack;
};
//入栈
void Push_SeqStack(SeqStack* stack, void* data){
if (stack == NULL){
return;
}
if (stack->size == MAX_SIZE){
return;
}
if (data == NULL){
return;
}
stack->data[stack->size] = data;
stack->size++;
};
//返回栈顶元素
void* Top_SeqStack(SeqStack* stack){
if (stack == NULL){
return NULL;
}
if (stack->size == 0){
return NULL;
}
return stack->data[stack->size-1]; //数组下标那个减一啥的
};
//出栈
void* Pop_SeqStack(SeqStack* stack){
if (stack == NULL){
return NULL;
}
if (stack->size == 0){
return NULL;
}
stack->data[stack->size -1] = NULL;
stack->size--;//size--就足够了 【可以不用上一步】
};
//判断是否为空
int IsEmpty(SeqStack* stack){
if (stack == NULL){
return -1;
}
if (stack->size == 0){
return SEQSTACK_TRUE;
}
return SEQSTACK_FALSE;
};
//返回栈中元素的个数
int Size_SeqStack(SeqStack* stack){
return stack->size;
};
//清空栈
void Clear_SeqStack(SeqStack* stack){
if (stack == NULL){
return;
}
for(int i=0;i<stack->size ;i++){
stack->data [i] = NULL;
}
stack->size = 0;//其实有这一步骤就够了,上面的for循环可以不用
};
//销毁
void FreeSpace_SeqStack(SeqStack* stack){
if(stack == NULL){
return;
}
free(stack);
};
typedef struct PERSON{
char name[64];
int age;
}Person;
int main(void){
//创建栈
SeqStack* stack = Init_SeqStack();
//创建数据
Person p1 = {"aaa",30};
Person p2 = {"bbb",20};
Person p3 = {"ccc",40};
Person p4 = {"ddd",60};
Person p5 = {"eee",80};
//入栈
Push_SeqStack(stack,&p1);
Push_SeqStack(stack,&p2);
Push_SeqStack(stack,&p3);
Push_SeqStack(stack,&p4);
Push_SeqStack(stack,&p5);
//输出
while (Size_SeqStack(stack) > 0){
//访问栈顶元素
Person* person = (Person*)Top_SeqStack(stack); //强制转换符号
printf("Name:%s Age:%d\n",person->name,person->age);
//弹出栈顶元素
Pop_SeqStack(stack);
}
//释放内存
FreeSpace_SeqStack(stack);
system("pause");
return 0;
}
顺序栈的完整C语言实现(含测试例子)
最新推荐文章于 2024-04-13 11:54:38 发布