实现思路->:
第零步,先创建一个结构体,里面有三个元素,一个元素 记载最大容量,一个元素记载当前容量,另一个元素存储有效元素(最好是指针,因为顺序表涉及扩容)。
第一步,初始化结构体,最大容量为0,当前容量为0,暂且不存储任何有效元素。
第二步,增加一个元素,增加过程中发现最大容量为0无可用空间,需要增加空间。
第三步,增加最大容量,使用 malloc 或 calloc 加 memcpy 。或 单独使用realloc 给结构体中的存储有效元素的元素开辟4个空间,之后每次空间不足 都将增加两倍大小。
第四步,空间增加成功后 添加一个元素,元素添加成功。
第五步,按照先进后出,后进先出的顺序 取出一个元素。
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct zhanshuzu //创建栈区类型
{
int* arr;
int max_counter = 0;
int counter = 0;
}zhanshuzu;
void init(zhanshuzu* a)//初始化结构体
{
a->counter = 0;
a->max_counter = 0;
a->arr = NULL;
}
void Expansion(zhanshuzu** p)//如果数组容量不够那就扩容 第一次扩容四个 之后每次扩容两倍
{
((*p)->max_counter == 0) ? (*p)->max_counter = 4 : (*p)->max_counter *= 2;
//(*p)->arr = (int*)malloc(sizeof(int)*(*p)->max_counter);
(*p)->arr = (int*)realloc((*p)->arr, sizeof(int)*(*p)->max_counter);
}
void add(zhanshuzu* p)
{
assert(p);
if (p->counter == p->max_counter)//如果数组元素个数,等于数组大小 那么扩容。
{
Expansion(&p);
}
int a = 0;
printf("进栈->:");
scanf_s("%d", &a);
p->arr[p->counter] = a;
p->counter++;
}
void Out_of_the_stack(zhanshuzu* p)//出栈
{
assert(p);
p->counter--;
printf("出栈->:%d\n", p->arr[p->counter]);
}
int main()
{
zhanshuzu* a = (zhanshuzu*)malloc(sizeof(zhanshuzu));
init(a);
add(a);
add(a);
add(a);
printf("\n");
Out_of_the_stack(a);
Out_of_the_stack(a);
Out_of_the_stack(a);
return 0;
}