C語言實現順序存儲結構(數組)
#include <stdio. h>
#include <malloc.h>
#include <stdlib.h>
struct Array
{
int* pBase; //數組首元素地址
int length; //數組總長度
int cnt; //數組當前元素個數
};
//數組初始化
void init_arr(struct Array * pArr, int length)
{
pArr->pBase = (int*)malloc(sizeof(int) * length);
if (pArr->pBase == NULL)
{
printf("內存分配失敗!\n");
exit(-1);
}
else
{
pArr->length = length;
pArr->cnt = 0;
}
}
//數組是否為空
int is_empty(struct Array *pArr)
{
if (pArr->cnt == 0)
{
return 0;
}
return -1;
}
//數組是否已滿
int is_full(struct Array *pArr)
{
if (pArr->cnt == pArr->length)
{
printf("數組已滿\n");
return 0;
}
return -1;
}
//數組追加
int append(struct Array *pArr, int e)
{
if ( is_full(pArr) == 0 )
{
return -1;
}
else
{
pArr->pBase[(pArr->cnt)++] = e;
}
}
//在pos之前插入元素e
int insert(struct Array *pArr, int pos, int e)
{
int i;
if ( is_full(pArr) == 0 )
{
return -1;
}
if (pos < 1 || pos > pArr->cnt+1)
{
printf("位置錯誤,插入失敗!\n");
return -1;
}
else
{
for (i=pArr->cnt-1; i>=pos-1; i--)
{
pArr->pBase[i + 1] = pArr->pBase[i];
}
pArr->pBase[pos - 1] = e;
pArr->cnt++;
}
}
//移除pos位置的元素
int remove_element(struct Array * pArr, int pos)
{
int i;
if (is_empty(pArr) == 0)
{
printf("數組為空,刪除失敗!\n");
return -1;
}
if (pos < 1 || pos > pArr->cnt)
{
printf("位置錯誤,刪除失敗!\n");
return -1;
}
for (i=pos; i<=pArr->cnt-1; i++)
{
pArr->pBase[i - 1] = pArr->pBase[i];
}
pArr->cnt--;
return 0;
}
//數組遍歷
void traverse(struct Array* pArr)
{
int i;
for (i=0; i<pArr->cnt; i++)
{
printf("%d ", pArr->pBase[i]);
}
printf("\n");
}
//數組倒置
void inverse(struct Array *pArr)
{
int i=0, j=pArr->cnt-1, t;
while (i < j)
{
t = pArr->pBase[i];
pArr->pBase[i] = pArr->pBase[j];
pArr->pBase[j] = t;
i++;
j--;
}
}
int main()
{
struct Array array;
init_arr(&array, 5);
append(&array, 1);
append(&array, 2);
append(&array, 3);
append(&array, 4);
insert(&array, 5, 0);
traverse(&array);
remove_element(&array, 5);
traverse(&array);
return 0;
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。