#include<bits/stdc++.h>
using namespace std;
typedef struct Arr{
int * pBase; //存储的是当前数组第一个元素地址
int len; //数组所能容纳最大元素的个数
int cnt; //当前数组有效元素的个数
/*需要用到allocate()函数
int increment; //自动增长因子
*/
}a1,*a2;
//a1 等价于 struct Arr; a2 等价于 struct Arr*
void init_arr(a2 pArr,int length); //初始化,长度
bool append_arr(a2 pArr,int value); //追加
bool insert_arr(a2 pArr,int value,int position); //插入
bool delete_arr(a2 pArr,int *pValue,int position); //删除
bool is_empty(a2 pArr); //判断是否空
bool is_full(a2 pArr); //是否满
void sort_arr(a2 pArr); //排序
void print_arr(a2 pArr); //输出
void inversion_arr(a2 pArr); //倒置
void free_arr(a2 pArr);
int main(){
a1 arr;
init_arr(&arr,6);
append_arr(&arr,1);
append_arr(&arr,3);
append_arr(&arr,5);
append_arr(&arr,7);
print_arr(&arr);
insert_arr(&arr,8,3);
print_arr(&arr);
int val;
delete_arr(&arr,&val,4);
printf("您所删除的数为:%d\n",val);
print_arr(&arr);
sort_arr(&arr);
print_arr(&arr);
inversion_arr(&arr);
print_arr(&arr);
free_arr(&arr); //等价于 free((&arr)->pBase);
return 0;
}
void inversion_arr(a2 pArr){
int i=0,t;
int j=pArr->cnt-1;
while(i<j){
t=pArr->pBase[i];
pArr->pBase[i]=pArr->pBase[j];
pArr->pBase[j]=t;
i++;
j--;
}
return;
}
void print_arr(a2 pArr){ //输出
if(is_empty(pArr)){
printf("数组为空!\n");
}
else{
for(int i=0;i<pArr->cnt;printf("%d ",pArr->pBase[i++]));
printf("\n");
}
}
void init_arr(a2 pArr,int length){
pArr->pBase =(int *)malloc(sizeof(int)*length);
if(pArr->pBase==NULL){
printf("动态内存分配失败!");
exit(-1); //终止整个程序
}
else{
pArr->len=length;
pArr->cnt=0;
}
return;
}
void free_arr(a2 pArr){
free(pArr->pBase);
}
bool append_arr(a2 pArr,int value){
if(is_full(pArr)){
return false;
}
else{
pArr->pBase[pArr->cnt++]=value;
return true;
}
}
bool insert_arr(a2 pArr,int value,int position){
if(is_full(pArr)){
return false;
}
if(position<1 || position>pArr->cnt+1){
return false;
}
for(int i=pArr->cnt-1;i>=position-1;i--){
pArr->pBase[i+1]=pArr->pBase[i];
}
pArr->pBase[position-1]=value;
return true;
}
bool delete_arr(a2 pArr,int *pValue,int position){
if(is_empty(pArr)) return false;
if(position<1 || position>pArr->cnt) return false;
*pValue=pArr->pBase[position-1]; //返回删除的值
for(int i=position;i<pArr->cnt;i++){
pArr->pBase[i-1]=pArr->pBase[i];
}
pArr->cnt--;
return true;
}
bool is_empty(a2 pArr){
return (pArr->cnt==0)?true:false;
/*if(pArr->cnt==0) return true;
else return false;*/
}
bool is_full(a2 pArr){
return (pArr->cnt==pArr->len)?true:false;
/*if(pArr->cnt==pArr->len) return true;
else return false;*/
}
void sort_arr(a2 pArr){
if(is_empty(pArr)){
printf("数组为空!\n");
}
else{
int t;
for(int i=0;i<pArr->cnt-1;i++){ //选择排序
int k=i;
for(int j=i+1;j<pArr->cnt;j++){
if(pArr->pBase[k]>pArr->pBase[j]) k=j;
}
if(k!=i){
t=pArr->pBase[k];
pArr->pBase[k]=pArr->pBase[i];
pArr->pBase[i]=t;
}
}
}
}
数据结构——线性表之连续存储数组(郝斌老师!)
最新推荐文章于 2021-11-25 21:37:00 发布