用 C 实现可扩容的顺序栈(数组 + 动态扩容)
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
# 编译产物
|
||||
*.exe
|
||||
*.o
|
||||
|
||||
# 本地笔记(仓库是 public,不提交)
|
||||
CLAUDE.md
|
||||
|
||||
# 编辑器/机器相关配置
|
||||
.vscode/
|
||||
@@ -0,0 +1,118 @@
|
||||
#include<stdio.h>
|
||||
#include<string.h>
|
||||
#include<malloc.h>
|
||||
#include<stdlib.h>
|
||||
|
||||
|
||||
|
||||
typedef struct
|
||||
{
|
||||
/* data */
|
||||
int length;//初始默认数组长度,随着数组扩充同步增加
|
||||
int add;//空位不够的时候一次增加的个数
|
||||
int top;//当前数组的位置
|
||||
int *start;//起始位置的指针,老师上课写了我也不知道为什么
|
||||
|
||||
}zhan;
|
||||
|
||||
|
||||
|
||||
int zadd(zhan *z,int x);
|
||||
void zinit(zhan *z);
|
||||
int zreduce(zhan *z,int *a);
|
||||
void zfree(zhan *z);
|
||||
|
||||
int main (){
|
||||
zhan z;
|
||||
int a;
|
||||
int num;
|
||||
zinit(&z);
|
||||
printf("要输入多少个数字呢");
|
||||
scanf("%d",&num);
|
||||
for(int i=0;i<num;i++){
|
||||
scanf("%d",&a);
|
||||
zadd(&z,a);
|
||||
}
|
||||
|
||||
printf("输出全部数字\n"); //输出数字
|
||||
for(int i=0;i<(z.top);i++){
|
||||
printf("%d",z.start[i]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
printf("现在开始出栈\n");
|
||||
// int b;
|
||||
// int c=zreduce(&z,&b);
|
||||
// if(!c){
|
||||
// printf("%d",b);
|
||||
// }
|
||||
// c=zreduce(&z,&b);
|
||||
// if(!c){
|
||||
// printf("%d",b);
|
||||
// }
|
||||
|
||||
|
||||
//出栈
|
||||
while (z.top!=0)
|
||||
{
|
||||
/* code */
|
||||
int b;
|
||||
int c=zreduce(&z,&b);
|
||||
if(!c){
|
||||
printf("%d",b);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
printf("结束111");
|
||||
zfree(&z);
|
||||
printf("结束222");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int zadd(zhan *z,int x){ //往栈里面加入新的元素
|
||||
//怎么加? 先看满没。满了就先扩容再加。没满则直接加上去,然后top+1
|
||||
if(z->top==z->length){
|
||||
z->start=(int*)realloc(z->start,(z->length+z->add)*sizeof(int));
|
||||
z->length=z->length+z->add;
|
||||
}
|
||||
z->start[z->top]=x;
|
||||
z->top++;
|
||||
|
||||
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
void zinit(zhan *z){ //创建栈 要传入啥呢?和定义zhan的东西好像一样。
|
||||
z->add=2;
|
||||
z->top=0;
|
||||
z->length=10; //现在定义好了,要申请内存
|
||||
z->start=(int*)malloc((z->length)*sizeof(int));
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
int zreduce(zhan *z,int *a){ //实现拿出去数据。这里 因为要把数据带着,要么 return ,要么用指针
|
||||
if(z->top==0){
|
||||
printf("没东西了,要爆了");
|
||||
return 1 ;
|
||||
}
|
||||
|
||||
z->top--;
|
||||
*a=z->start[z->top];
|
||||
return 0;
|
||||
|
||||
}
|
||||
|
||||
void zfree(zhan *z){
|
||||
free(z->start);
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user