线性表的基本实现

线性表的顺序存储又称为顺序表,顺序表的关键在于理解逻辑上相邻的元素在物理位置上也相邻。代码实现较为简单,但需要注意线性表中的位序是从1开始的,这点和数组下标从0开始有一定的区别,在进行删除和查找的操作时需要注意题目所给的条件,是位序还是数组下标。

#include <iostream>
#include <cstdlib>

using namespace std;

#define ElemType int
#define InitSize 10

typedef struct {
    ElemType *data;
    int MaxSize;
    int length;
} SqList;

void InitList(SqList &L);

void IncreaseSize(SqList &L, int len);

bool ListInsert(SqList &L, int i, ElemType e);

bool ListDelete(SqList &L, int i, ElemType &e);

int LocateElem(SqList L, ElemType e);

int GetElem(SqList L, int i);

int Length(SqList L);

bool Empty(SqList L);

void PrintList(SqList L);

bool DestroyList(SqList &L);


int main() {
    SqList L;
    InitList(L);
    ListInsert(L, 1, 1);
    ListInsert(L, 1, 3);
    ListInsert(L, 1, 4);
    PrintList(L);

    cout << "第二个元素为" << GetElem(L, 2) << endl;
    cout << "the len of L is " << Length(L) << endl;
    cout << "the locate 4 in  " << LocateElem(L, 4) << endl;

    int delVal;
    ListDelete(L, 2, delVal);
    cout << "the delete val is " << delVal << endl;

    PrintList(L);
    return 0;
}

void InitList(SqList &L) {
    //动态分配内存
    L.data = (ElemType *) malloc(InitSize * sizeof(ElemType));
    L.length = 0;
    L.MaxSize = InitSize;
}

void IncreaseSize(SqList &L, int len) {
    int *p = L.data;
    L.data = (ElemType *) malloc(sizeof(ElemType) * (L.MaxSize + len));
    for (int i = 0; i < L.length; ++i) {
        L.data[i] = p[i];
    }
    L.MaxSize += len;
    free(p);
}

/**
 * 把第i个元素以及后面的元素依次往后挪一位
 * @param L
 * @param i 表示线性表的位序,从1开始,对应数组下标加1
 * @param e
 */
bool ListInsert(SqList &L, int i, ElemType e) {
    //判断输入是否合法
    if (i < 1 || i > L.length + 1 || L.length >= L.MaxSize) {
        return false;
    }

    for (int j = L.length; j >= i; --j) {
        L.data[j] = L.data[j - 1];
    }
    L.data[i - 1] = e;
    L.length++;
    return true;
}

bool ListDelete(SqList &L, int i, ElemType &e) {

    //判断输入的合法性,删除的位置不能越界
    if (i < 1 || i > L.length) {
        return false;
    }

    //将要删除的元素取出,并将后面的元素依次往前挪一位
    e = L.data[i - 1];
    for (int j = i; j < L.length; ++j) {
        L.data[j - 1] = L.data[j];
    }
    L.length--;
    return true;
}

/**
 * 根据元素的值进行查找
 * @param L
 * @param e
 * @return 查找的元素值的位序,没找到元素就返回-1
 */
int LocateElem(SqList L, ElemType e) {
    for (int i = 0; i < L.length; ++i) {
        if (L.data[i] == e)
            return i + 1;
    }
    return -1;
}

int GetElem(SqList L, int i) {
    if (i < 1 || i > L.length) {
        return -1;
    }
    return L.data[i - 1];
}

int Length(SqList L) {
    return L.length;
}

bool Empty(SqList L) {
    return L.length == 0;
}

void PrintList(SqList L) {
    for (int i = 0; i < L.length; ++i) {
        printf("%d ", L.data[i]);
    }
    printf("\n");
}

//判断表是否为空
bool DestroyList(SqList &L) {
    if (Empty(L))
        return false;
    free(L.data);
    return true;
}