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;
}

發佈了33 篇原創文章 · 獲贊 10 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章