c语言指针实现java的ArrayList操作
在学习数据结构的同时进行实践,使用指针的方式对数组进行操作,最终完成java中类似ArrayList的操作方法。
#include<stdio.h>
#include <malloc.h>
#include<stdlib.h>
struct data
{
int* pst;
int lent;
int cnt;
};
void ini_arr(struct data* pst,int length);
bool is_empty(struct data* pst);
bool is_full(struct data* pst);
void show_arr(struct data* pst);
bool append_arr(struct data* pst,int val);
bool insert_arr(struct data* pst, int val,int pos);
bool delete_arr(struct data* pst, int pos);
int get(struct data* pst, int pos);
void sort_arr(struct data* pst);
void inversion_arr(struct data* pst);
int main() {
//printf("hello world");
struct data pst;
int len = 6;//length of arr
int g = 3;
ini_arr(&pst,len);
append_arr(&pst, 1);
append_arr(&pst, 2);
append_arr(&pst, 5);
append_arr(&pst, 6);
insert_arr(&pst,3,1);
show_arr(&pst);
printf("删除2元素后的数组为:\n");
delete_arr(&pst,2);
show_arr(&pst);
int i = get(&pst,g);
printf("得到第%d个值为:%d",g,i);
inversion_arr(&pst);
printf("反转后的数组为:\n");
show_arr(&pst);
sort_arr(&pst);
printf("排序后的数组为:\n");
show_arr(&pst);
return 0;
}
void ini_arr(struct data* pst,int length) {
pst->pst = (int*)malloc(sizeof(int)*length);
if (pst->pst == NULL)
{
printf("初始化失败!\n");
exit(-1);
}
else
{
pst->cnt = 0;
pst->lent = length;
}
return;
}
bool is_empty(struct data* pst) {
if (pst->cnt == 0)
return true;
else
return false;
}
bool is_full(struct data* pst)
{
if (pst->cnt == pst->lent)
return true;
else
return false;
}
void show_arr(struct data* pst)
{
if (is_empty(pst))
{
printf("数组为空!\n");
}
else
{
for (int i = 0; i < pst->cnt; ++i) {
printf("%d ",pst->pst[i]);
}
printf("\n");
}
return;
}
bool append_arr(struct data* pst,int val)
{
if(is_full(pst))
{
printf("数组已满!\n");
return false;
}
else
{
pst->pst[pst->cnt] = val;
(pst->cnt)++;
return true;
}
}
bool insert_arr(struct data* pst, int val, int pos)
{
if (is_full(pst))
{
printf("数组已满\n");
return false;
}
else if(pos>pst->lent||pos<1)
{
printf("插入位置超出数组的大小!\n");
return false;
}
else
{
for (int i = pst->cnt; i > pos-1; --i)
{
pst->pst[i] = pst->pst[i - 1];
}
pst->pst[pos-1] = val;
pst->cnt++;
return true;
}
}
bool delete_arr(struct data* pst, int pos)
{
if (is_empty(pst)){
printf("数组为空!\n");
return false;
}
else if (pos>pst->cnt)
{
printf("超出数组数据大小\n");
return false;
}
else
{
for (int i = pos - 1; i < pst->cnt - 1; ++i) {
pst->pst[i] = pst->pst[i + 1];
}
pst->cnt--;
return true;
}
}
int get(struct data* pst, int pos)
{
if (pos > pst->cnt) {
printf("超出数组数据大小\n");
exit(-1);
}
else
{
int i = pst->pst[pos - 1];
return i;
}
}
//冒泡方式实现
void sort_arr(struct data* pst)
{
int i, j,c;
for (i = 0; i < pst->cnt; ++i)
{
for (j = i+1; j < pst->cnt; ++j)
{
if (pst->pst[i] > pst->pst[j])
{
c = pst->pst[i];
pst->pst[i] = pst->pst[j];
pst->pst[j] = c;
}
}
}
return;
}
void inversion_arr(struct data* pst)
{
int i = 0;
int j = pst->cnt - 1;
int c;
while (i < j)
{
c = pst->pst[i];
pst->pst[i] = pst->pst[j];
pst->pst[j] = c;
++i;
--j;
}
return;
}