#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct
{
int top; //栈顶标记
int *dataMemory; //内存大小
int maxSize; //元素最大个数
}STACK ,*LPSTACK;
//创建初始化的栈(1。创建空栈且确定存在,2.分配内存(类型转换 大小*数目)给予栈3.内存最大值为自己设定的maxsize,4.栈顶指针top指向初始位置)
//判断栈是否为空,在进行操作前自行调用
//进行入栈出栈,获取元素,确定大小等操作
LPSTACK creatStack(int maxSize) //创建初始栈
{
LPSTACK stack = (LPSTACK)malloc(sizeof(STACK));
assert(stack);
stack->dataMemory = (int *)malloc(sizeof(int)*maxSize);
stack->maxSize = maxSize;
stack->top = -1; //设定的初始栈顶位置
return stack;
}
int empty(LPSTACK pstack) //判断是否栈空,栈顶指针在初始位置,栈则空
{
return pstack->top == -1;
}
void pop_top(LPSTACK pstack, int *data) //获取栈顶元素与获取出栈元素
{
if (pstack == NULL || pstack->top == -1)
{
printf("栈为空,无法出栈");
return;
}
*data = pstack->dataMemory[pstack->top--]; //
}
void push(LPSTACK pstack, int data) //入栈
{
if (pstack == NULL)
{
return;
}
if (pstack->top + 1 == pstack->maxSize) //栈顶加一到达设定的最大值(即top到达最大数组下标),栈满
{
printf("栈满了!\n");
}
pstack->dataMemory[++pstack->top] = data; //没满,向数组下标(需要通过运算top达到从零开始)绑定的内存段存储数据
}
void pop(LPSTACK pstack) //出栈
{
if (pstack == NULL || pstack->top == -1)
{
printf("栈空,无法出栈\n");
}
pstack->top--; //伪栈空
}
int top(LPSTACK pstack) //获取栈顶元素
{
return pstack->dataMemory[pstack->top];
}
int size(LPSTACK pstack) //栈存储数据的数目(通过栈顶指针+初始栈顶指针到数组最小下标0之间的差距量,如果为负整数,则等于top+负XXX)
{
return pstack->top + 1;
}
int main()
{
LPSTACK pstack = creatStack(10);
for (int i = 0; i < 5; i++)
{
push(pstack, i);
}
printf("现在栈元素数目为:%d\n",size(pstack));
while (!empty(pstack))
{
printf("%d\t",top(pstack)); //获取栈顶元素
pop(pstack); //获取后将元素剔除,栈顶元素指向原top的下一个
}
printf("\n");
printf("现在栈元素数目为:%d\n", size(pstack));
return 0;
}
C语言数组栈
最新推荐文章于 2024-01-29 22:23:37 发布