#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
/******************************项目说明*******************************
栈
1 受限线性表
2 属于先进后出的数据结构
3 研究内容 :入栈、出栈、栈顶、元素个数
4 顺序存储
4.1 利用数组模拟出栈
4.2 设计:利用数组尾地址 做栈顶,对入栈出栈方便
4.3 对外接口设计
4.3.1 初始化
4.3.2 入栈
4.3.3 出栈
4.3.4 返回栈顶
4.3.5 返回元素个数
4.3.6 判断是否为空
4.3.7 销毁栈
********************************************************************/
//设计栈 结构体
#define MAX 1024
typedef struct __SSTACK
{
void*data[MAX];
int m_Size;
}SeqStack;
//对外隐身结构体属性
typedef void* SStack;
//初始化栈结构体
SStack init_SeqStack()
{
SeqStack*p = malloc(sizeof(SeqStack));
if (p==NULL)
{
return NULL;
}
memset(p, 0, sizeof(SeqStack));
return p;
}
//入栈
void push_SeqStack(SStack handle,void*data)
{
if (handle==NULL||data==NULL)
{
return;
}
SeqStack*p = handle;
if (p->m_Size==MAX)
{
return;
}
p->data[p->m_Size] = data;
p->m_Size++;
}
//出栈
void pop_SeqStack(SStack handle)
{
if (handle == NULL)
{
return;
}
SeqStack*p = handle;
p->m_Size--;
p->data[p->m_Size] = NULL;
}
//返回栈顶
void* top_SeqStack(SStack handle)
{
if (handle == NULL)
{
return;
}
SeqStack*p = handle;
return p->data[--p->m_Size];
}
//返回元素个数
int size_SeqStack(SStack handle)
{
if (handle == NULL)
{
return -1;
}
SeqStack*p = handle;
return p->m_Size;
}
//判断是否为空
int isEmpty_SeqStack(SStack handle)
{
if (handle == NULL)
{
return -1;
}
SeqStack*p = handle;
if (p->m_Size==0)
{
return 1;
}
return 0;
}
//销毁栈
void destory_SeqStack(SStack handle)
{
if (handle == NULL)
{
return -1;
}
SeqStack*p = handle;
free(p);
}
/************用户区************/
typedef struct __HERO
{
char name[64];
int attack;
}Hero;
void test()
{
Hero h1 = { "张飞",85 };
Hero h2 = { "赵云",95 };
Hero h3 = { "刘备",78 };
Hero h4 = { "关羽",93 };
Hero h5 = { "曹操",81 };
Hero h6 = { "孙权",72 };
Hero h[3] =
{
{ "孙尚香",77 },
{ "大乔",65 },
{ "黄盖",85 }
};
SStack handle = init_SeqStack();
push_SeqStack(handle, &h1);
push_SeqStack(handle, &h2);
push_SeqStack(handle, &h3);
push_SeqStack(handle, &h4);
push_SeqStack(handle, &h5);
push_SeqStack(handle, &h6);
printf("栈区大小:%d\n", size_SeqStack(handle));
printf("--------------------------\n");
pop_SeqStack(handle);
printf("栈区大小:%d\n", size_SeqStack(handle));
printf("--------------------------\n");
while(!isEmpty_SeqStack(handle))
{
Hero*tmp = top_SeqStack(handle);
printf("%s\t%d\n",tmp->name,tmp->attack);
}
printf("--------------------------\n");
printf("栈区大小:%d\n", size_SeqStack(handle));
printf("--------------------------\n");
push_SeqStack(handle, &h1);
push_SeqStack(handle, &h2);
while (!isEmpty_SeqStack(handle))
{
Hero*tmp = top_SeqStack(handle);
printf("%s\t%d\n", tmp->name, tmp->attack);
}
destory_SeqStack(handle);
printf("--------------------------\n");
}
int main()
{
test();
system("pause");
return 0;
}
数据结构与算法_C语言栈型数据案例
最新推荐文章于 2022-09-04 10:47:26 发布