C++順序表實現

手寫了一波C++順序表,加深理解。

實現目標(對應js中array對象的部分內建函數實現):

1.創建數組
2.刪除數組
3.顯示數組每個元素
4.獲取數組指定位子的元素
5.查找元素
6.指定位子插入元素
7.刪除數組中指定元素
    void CreateList(SqList *&L, ElemType a[], int n); // 建立順序表
    void DestroyList(SqList *&L);
    void ListEmpty(SqList *L);
    int ListLength(SqList *L);
    void DispList(SqList *L); // 顯示數組每哥元素
    bool GetElem(SqList *L, int i, ElemType &e); // 求某個位置數據元素的值(1開始)
    int LocateElem(SqList *L, ElemType e); // 查找元素
    bool ListInsert(SqList *&L, int i, ElemType e); // 插入元素(讓第i個位置開始的所有元素一起後移)
    bool ListDelete(SqList *&L, int i, ElemType &e); // 刪除元素

部分代碼:

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef int ElemType;

typedef struct
{
    ElemType data[MAX_SIZE];
    int length;
}SqList;


int main() {
    printf("start\n");
    SqList *L = NULL;
    int n = 5;
    ElemType arr[5] = {1, 2, 3, 4, 5};
    ElemType newArr[5] = {7, 8, 9, 10, 6};

    CreateList(L, newArr, n);
    DispList(L);
    ListLength(L);

    ElemType result = 0;
    GetElem(L, 1, result);
    printf("GetElem: %d\n", result);

    int locate = -1;
    locate = LocateElem(L, 4);
    printf("locate: %d\n", locate);

    ListInsert(L, 1, 1);
    DispList(L);

    ElemType delResult = -1;
    ListDelete(L, 4, delResult);
    DispList(L);
    printf("del: %d\n", delResult);

    return 0;
}

void CreateList(SqList *&L, ElemType a[], int n) {
    L = (SqList *)malloc(sizeof(SqList));
    for (int i = 0; i < n; i++) {
        L->data[i] = a[i];
    };
    L->length = n;
}

void DispList(SqList *L) {
    for (int i = 0; i < L->length; i++) {
        printf("index: %d, value: %d;\n", i, L->data[i]);
    };
    printf("\n");
}

int ListLength(SqList *L) {
    printf("length: %d\n", L->length);
    return L->length;
}

bool GetElem(SqList *L, int i, ElemType &e) {
    if (i <= 0 || i > L->length) {
        return false;
    }
    e = L->data[i - 1];
    return true;
}

int LocateElem(SqList *L, ElemType e) {
    ElemType result = -1;
    for (int i = 0; i < L->length; i++) {
        if (L->data[i] == e) {
            result = i;
            break;
        }
    }
    return result;
}

bool ListInsert(SqList *&L, int i, ElemType e) {
    int realIndex = i - 1;

    if (realIndex < 0 || realIndex > L->length) {
        return false;
    }

    L->length++;

    for (int index = L->length; index > realIndex && index > 0; --index) {
        L->data[index] = L->data[index - 1];
    }

    L->data[realIndex] = e;

    return true;
}

bool ListDelete(SqList *&L, int i, ElemType &e) {
    if (i < 0 || i >= L->length) {
        return false;
    }
    e = L->data[i - 1];
    L->length--;
    for (int index = i - 1; index < L->length; index++) {
        L->data[index] = L->data[index + 1];
    }
    return true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章