2. 线性表的顺序结构

线性表是具有相同类型的n(n>=0)个元素的有限序列,其中n为表长,当n=0时,该表为空表

线性表的九种基本操作:

图片

图片

一、顺序表的定义

我们采用数组动态分配的方法

#define MaxSize 50
#define ElemType int
typedef struct 
{
    ElemType *data; //数组的空间大小动态分配
    int length;
}SqList;

初始化时动态分配地址空间:

void InitList(SqList *&L,ElemType a[],int n)
{
    L=(SqList *)malloc(sizeof(SqList));
    //动态声明数组空间
    L->data = (ElemType *)malloc(sizeof(ElemType)*MaxSize);
    for (int i=0;i<n;i++)
        L->data[i]=a[i];
    L->length=n;
}

二、插入操作

  1. 判断插入是否超过了边界(1 ~ n+1)
  2. 判断数组有没有满
  3. 插入位置之后的每个数据元素往后移一位
  4. 插入数据
//前插
bool ListInsert(SqList *&L, int i, ElemType e){
    //判断是否超过边界
    if(i < 1 || i > L->length + 1)
        return false;
    //判断数组有没有满
    if(L->length >= 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;
}

四、查找

  1. 因为不需要更改,所以不用传引用
  2. 返回的是元素在表中的下标+1
//按值查找,返回顺序表的表号
int LocateElem(SqList *&L, ElemType e){
    int i;
    for(i = 0; i<L->length; i++){
        if(L->data[i] == e)
            return i+1;
    }
    return 0;//查找失败
}

最好时间复杂度:O(1)
平均时间复杂度:Pi(查找概率) = 1/n,查找次数i,∑Pi*i = (1+n)/2,O(n)

最坏时间复杂度:O(n)

五、删除顺序表

void DestroyList(SqList *&L)
{
    free(L->data);
	free(L);
}

六、测试

int main(){
    ElemType a[3] = {1,2,3};
    SqList *L;
    ElemType e;
    InitList(L, a, 3);
    ListInsert(L, 1, 0);
    ListDelete(L,4,e);
    printf("the element deleted: %d", e);
    DestroyList(L);
    system("pause");
}
原文地址:https://www.cnblogs.com/theory/p/13338755.html