初学数据结构,为自己的学习做一些笔记,先列一个思维导图,然后直接上代码。
核心部分当然是如何实现对数组的操作,下面是整体代码。
/*
2018年12月16日09:01:12
目的:学习定义数组的函数,感受指针的魅力。
*/
# include <stdio.h>
# include <stdlib.h>
struct Arr
{
int * pBase; //存储的是数组第一个元素的地址
int len; //数组所能容纳的最大元素的个数
int cnt; //当前数组有效元素的个数
int increment //自动增长因子
};
void init_arr(struct Arr * pArr, int length); //初始化
bool append_arr(struct Arr * pArr, int val); //追加
bool insert_arr(struct Arr * pArr, int pos, int val); //插入
bool delete_arr(struct Arr * pArr, int pos, int * pVal); //删除
int get(); //获取数组中某个值
bool is_empty(strcut Arr * pArr); //判断数组是否为空
bool is_full(); //判断数组是否已满
void sort_arr(struct Arr * pArr); //排序
void show_arr(strcut Arr * pArr ); //输出数组元素
void inversion_arr(struct Arr * pArr); //倒置
int main(void)
{
struct Arr arr;
init_arr(&arr, 6);
show_arr(&arr);
return 0;
}
void init_arr(struct Arr * pArr, int length)
{
pArr->pBase = (int *)malloc(sizeof(int) * length);
if (NULL == pArr->pBase)
{
printf("abort!\n");
exit(-1); //终止整个程序
}
else
{
pArr->len = length;
pArr->cnt = 0;
}
return;
}
bool is_empty(strcut Arr * pArr)
{
if (0 == pArr->cnt)
return true;
else
return false;
}
bool is_full(struct Arr * pArr)
{
if (pArr->cnt == pArr->len)
return true;
else
return fasle;
}
void show_arr(struct Arr * pArr)
{
if ( is_empty(pArr) )
{
printf("数组为空!\n");
}
else
{
for (int i=0; i<pArr->cnt; ++i)
printf("%d ", pArr->pBase[i]);
printf("\n");
}
}
bool append_arr(struct Arr * pArr, int val)
{
if ( is_full(pArr) )
return false;
else
{
pArr->pBase[pArr->cnt] = val;
(pArr->cnt)++;
}
}
bool insert_arr(struct Arr * pArr, int pos, int val)
{
int i;
if (is_full(pArr))
return false;
if (pos<1 || pos>pArr->cnt+1)
return false;
for (i=pArr->cnt-1; i>=pos-1; --i)
{
pArr->pBase[i+1] = pArr->pBase[i]
}
pArr->pBase[pos-1] = val;
pArr->cnt++;
return true;
}
bool delete_arr(struct Arr * pArr, int pos, int * pVal)
{
if (is_empty(pArr))
return false;
if (pos<1 || pos>pArr->cnt)
return false;
*pVal = pArr->pBase[pos-1];
for (i=pos; i<pArr->cnt; ++i)
{
pArr->pBase[i-1] = pArr->pBase[i];
}
pArr->cnt--;
return true;
}
void inversion_arr(struct Arr * pArr)
{
int i = 0;
int j = pArr->cnt;
int t;
while (i < j)
{
t = pArr->pBase[i];
pArr->pBase[i] = pArr->pBase[j];
pArr->pBase[j] = t;
++i;
--j;
}
return;
}
void sort_arr(struct Arr * pArr)
{
int i, j, t;
for (i=0; i<pArr->cnt; ++i)
{
for (j=i+1; j<pArr->cnt; ++j)
{
if (pArr->pBase[i] > pArr->pBase[j])
{
t = pArr->pBase[i];
pArr->pBase[i] = pArr->pBase[j];
pArr->pBase[j] = t;
}
}
}
}
版权声明:本文为sinat_42421829原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。