线性结构
所有数据在内存地址中是连续存储的
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//自定义数组结构体 是一个复合的数据类型
struct MyArray
{
int * pBase; //数组中第一个数据元素的【地址】 (占4个字节)
int len; //数组长度
int cnt; //当前数组中有效元素的个数
};
//定义操作
void initArray(struct MyArray *,int);
bool appendArray(struct MyArray *,int val);
bool insertArray(struct MyArray *, int pos ,int val); //pos 从1开始
bool deleteArray(struct MyArray *, int pos ,int * pVal);
bool isEmpty(struct MyArray *);
bool isFull(struct MyArray *);
void visitArray(struct MyArray *);
void sortArry();
void inversionArry();
bool get();
int main(void)
{
struct MyArray arr;
initArray(&arr,13);
appendArray(&arr,1);
appendArray(&arr,2);
appendArray(&arr,3);
appendArray(&arr,5);
printf("删除之前遍历数组\n");
visitArray(&arr);
int val;
deleteArray(&arr,1 ,&val);
printf("删除的数据的值=%d \n" , val);
printf("删除之后遍历数组\n");
visitArray(&arr);
return 0;
}
//函数实现
void initArray(struct MyArray * pArr,int initSize)
{
pArr->pBase = (int *) malloc(sizeof(int) * initSize);
if(pArr->pBase == NULL)
{
printf("Error 动态分配内存失败");
exit(-1);
}else{
pArr->len = initSize;
pArr->cnt = 0;
}
}
bool isEmpty(struct MyArray * pArr){
if(pArr->cnt == 0)
{
return true;
}else{
return false;
}
}
void visitArray(struct MyArray * pArr)
{
if(isEmpty(pArr))
{
printf("数组为空程序退出");
}else{
printf("总共有%d个元素\n",pArr->cnt);
for(int i = 0; i<pArr->cnt; ++i)
{
printf("(cnt=%d 的值)%d ",i,pArr->pBase[i]);//自行理解此处
}
printf("\n");
}
}
bool isFull(struct MyArray * pArr)
{
if(pArr->cnt == pArr->len){
return true;
}
return false;
}
bool appendArray(struct MyArray * pArr, int val)
{
if(isFull(pArr))
{
return false;
}
else
{
printf("插入之前pArr->cnt= %d \n",pArr->cnt);
//追加数据
pArr->pBase[pArr->cnt] = val;
(pArr->cnt)++;
return true;
}
}
bool insertArray(struct MyArray * pArr, int pos ,int val)
{
if(pos<1 || pos > pArr->cnt+1)
{
printf("pos=%d不合法 数据插入失败\n",pos);
return false;
}
if(isFull(pArr))
{
return false;
}
else
{
int i;
//插入数据
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 deleteArray(struct MyArray * pArr, int pos ,int * pVal)
{
if(pos<1 || pos > pArr->cnt+1)
{
printf("pos=%d不合法 删除数据失败\n",pos);
return false;
}
else if(isEmpty(pArr))
{
return false;
}
else
{
*pVal = pArr->pBase[pos-1];
int i;
for(i = pos ; i < pArr->cnt ; ++i)
{
pArr->pBase[i-1] = pArr->pBase[i];
}
(pArr->cnt)--;
return true;
}
}