线性表的顺序存储

  1. 逻辑上相邻的元素,物理上也相邻
  2. 逻辑位序和物理位序相差1
  3. 预定义的常量
    #define TRUE 1
    #define FALSE 0
    #define OK 1
    #define ERROR 0
    #define INFEASIBLE -1
    #define OVERFLOW -2
    typedef int Status;
    typedef char ElemType;

     

  4. 顺序表的定义

        静态存储:    

    #define MAXSIZE 100
    typedef struct{
        ElemType elem[MAXSIZE];
        int length;
    }SqList;

                 动态存储:

    typedef struct{
        ElemType *elem;
        int length;
    }SqList;
    L.elem = new ElemType(MAXSIZE);//或者
    L.elem = (ElemType*)malloc(sizeof(ElemType)*MAXSIZE);
    
  5. 线性表L的初始化
Status InitList_Sq(SqList &L){
    L.elem = new ElemType[MAXSIZE];
    if(!L.elem)exit(OVERFLOW);//存储分配失败
    L.length = 0;
    return OK;
}

    6.销毁线性表L

void DestroyList(SqList &L){
    if(L.elem)
    delete L.elem;//释放存储空间
}

   7.清空线性表L

void ClearList(SqList &L){
    L.length = 0;
}

   8.求线性表的长度

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

   9.判断线性表L是否为空

int IsEmpty(SqList L){
    if(L.length == 0)return 1;
    else return 0;
}

  10.顺序表的取值

           时间复杂度O(1)

int GetElem(SqList L, int i, ElemType &e){
    if(i<1||i>L.length)return ERROR;//判断i值是否合理
    e=L.elem[i-1];//第i-1的单元存储着第i个元素
    return OK;
}

11.线性表的查找

         顺序查找

         ASL(Average Search Length)每个元素的查找次数之和除以元素的个数。

int LocateElem(SqList L,ElemType e){
    for(i=0;i<L.length;i++)
        if(L.elem[i]==e)return i+1;//查找成功,返回序号
    return 0;
}

12.线性表的插入

         插入位置:

                     1.最后 2.中间  3.最前面

Status ListInsert_Sq(SqList &L, int i, ElemType e){
    if(i<1||i>L.length+1)
        return ERROR;
    if(L.length == MAXSIZE)
        return ERROR;
    for(j = L.length - 1;j >= i-1;j--)
        L.elem[j+1] = L.elem[j];           //遍历整个表,移动之后每一个元素
    L.elem[i-1] = e;      //将e放入第i个位置
    L.length++;
    return OK;
}

13.线性表的删除

          时间复杂度O(n)

Status ListDelete_Sq(SqList &L, int i){
    if((i<1)||(i>length))
        return ERROR;
    for(j=i;j<L.length-1;j++)
        L.elem[j-1]=L.elem[j];
    L.length--;
    return OK;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值