2 Star 0 Fork 0

mtgo/dataStructure_alogrithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sqStack.c 2.90 KB
一键复制 编辑 原始数据 按行查看 历史
mtgo 提交于 2022-02-22 21:51 . commit all file
//栈的顺序存储
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 1024
//栈的结构体
struct SStack
{
//将数组头作为栈尾,因为如果作为栈顶的话来回出入元素时间开销比较大
void *data[MAXSIZE]; //数组
int size;
};
typedef void * sstack;
//初始化栈
sstack init_stack(){
struct SStack * myStack = malloc(sizeof(struct SStack));
if (myStack==NULL)
{
return NULL;
}
memset(myStack->data,0,sizeof(void *)*MAXSIZE); //给数组赋初值0
myStack->size=0; //初试化栈的大小
return myStack;
}
//入栈
void push_stack(sstack stack,void *data ){
if (stack==NULL)
{
return;
}
if (data==NULL)
{
return;
}
struct SStack *myStack=stack; //把用户传过来的指针转换成栈结构体指针
//判断栈满
if (myStack->size==MAXSIZE)
{
return;
}
//入栈就是尾插数组
myStack->data[myStack->size]=data;
myStack->size++;
}
//出栈
void pop_stack(sstack stack){
if (stack==NULL)
{
return;
}
struct SStack *myStack=stack;
//判断栈空
if (myStack->size==0)
{
return;
}
//出栈其实就是尾删
myStack->data[myStack->size-1]=NULL;
myStack->size--;
}
//返回栈顶
void * top_stack(sstack stack)
{
if (stack == NULL)
{
return NULL;
}
struct SStack * mystack = stack;
if (mystack->size == 0)
{
return NULL;
}
return mystack->data[mystack->size - 1];
}
//判断栈是否为空
int isempty_stack(sstack stack){
if (stack==NULL)
{
return -1; //返回-1代表栈空
}
struct SStack *myStack=stack;
if (myStack->size==0)
{
return -1;
}
return 0;
}
//返回栈大小
int size_stack(sstack stack){
if (stack==NULL)
{
return -1;
}
struct SStack *myStack=stack;
return myStack->size;
}
//销毁栈
void destroy_stack(sstack stack){
if (stack==NULL)
{
return;
}
free(stack);
stack=NULL;
}
//测试
struct Person
{
char name[64];
int age;
};
void test01(){
//初始化栈
sstack myStack=init_stack();
//创建数据
struct Person p1 = { "aaa", 10 };
struct Person p2 = { "bbb", 20 };
struct Person p3 = { "ccc", 30 };
struct Person p4 = { "ddd", 40 };
struct Person p5 = { "eee", 50 };
//入栈
push_stack(myStack, &p1);
push_stack(myStack, &p2);
push_stack(myStack, &p3);
push_stack(myStack, &p4);
push_stack(myStack, &p5);
printf("栈的元素个数为:%d\n", size_stack(myStack));
while (isempty_stack(myStack)==0) //当栈不空时,元素依次出栈
{
struct Person *p=top_stack(myStack);
printf("姓名:%s,年龄:%d\n",p->name,p->age);
//元素出栈
pop_stack(myStack);
}
//销毁栈
destroy_stack(myStack);
}
int main()
{
test01();
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/mtgo666/data-structure-and-algorithm.git
git@gitee.com:mtgo666/data-structure-and-algorithm.git
mtgo666
data-structure-and-algorithm
dataStructure_alogrithm
master

搜索帮助