04 顺序存储的线性表 及线性表操作方法定义

线性表结构:

main.cpp:

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

using namespace std;

//函数结果状态代码
#define TRUE    1
#define FALSE   0
#define OK      1
#define ERROR   0
#define INFEASIBLE -1 //"不可能的"
#define OVERFLOW -2//"溢出,扩展出界"

//定义常量
#define MAXSIZE 100     //线性表可能达到的最大长度

typedef struct {
    char no[20];            //元素ISBN编号
    char name[50];      //元素名字
    float price;             //图书(元素)价格
} Book;

typedef struct{
    Book *elem;         //存储空间基地址
    int length;             //线性表中当前元素个数
} SqList;               //线性表的顺序存储结构类型为SqList

typedef int Status; //Status是函数的类型,其值是函数结果状态代码
typedef Book ElemType;

//方法
//线性表L初始化(参数用引用)
Status InitList(SqList &L);       //构造一个空的顺序表

//销毁线性表L
void DestroyList(SqList &L);

//清空线性表L
void ClearList(SqList &L);

//求线性表L的长度
int GetLength(SqList L);

//判断线性表是否为空
int IsEmpty(SqList L);

//获取线性表内容:取第i个元素
int GetElem(SqList L, int i, ElemType &e);

//查找:(顺序查找)按值查找(按给定书号进行查找,确定是否存在该图书)
/*
如果存在,输出是第几个元素
如果不存在,输出0
*/
int LocateElem(SqList L, ElemType e);

//插入操作:将元素e插在第i个位置上
Status ListInsert_Sq(SqList &L, int i, ElemType e);

//删除操作:删除第i个元素
Status ListDelete_Sq(SqList &L, int i);


int main()
{

    return 0;
}


//方法
//线性表L初始化(参数用引用)
Status InitList(SqList &L){             //构造一个空的顺序表
    L.elem = new ElemType[MAXSIZE];  //为顺序表分配空间
    if(!L.elem){
        exit(OVERFLOW);      //存储分配失败
    }
    L.length = 0;      //空表长度为0
    return OK;
}

//销毁线性表L
void DestroyList(SqList &L){
    if(L.elem){
        delete L.elem;      //释放存储空间(删除此数组)
    }
}

//清空线性表L
void ClearList(SqList &L){
    L.length=0;
}

//求线性表L的长度
int GetLength(SqList L){
    return (L.length);
}

//判断线性表是否为空
int IsEmpty(SqList L){
    if(L.length == 0){
        return 1;
    }else{
        return 0;
    }
}

//获取线性表内容:取第i个元素
int GetElem(SqList L, int i, ElemType &e){
    if(i<1 || i>L.length){//判断i值是否合理,若不合理,返回ERROR
        return ERROR;
    }
    e = L.elem[i-1];           //第(i-1)个单元存储着第i个数据
    return OK;
}

//查找:(顺序查找)按值查找(按给定书号进行查找,确定是否存在该图书)
/*
如果存在,输出是第几个元素
如果不存在,输出0
*/
int LocateElem(SqList L, ElemType e){
    for(int i=0; i<L.length; i++){
        if(L.elem[i].no == e.no){
            return (i+1);   //查找成功,返回序号
        }
    }
    return 0;               //查找失败,返回0
}

//插入操作:将元素e插在第i个位置上
Status ListInsert_Sq(SqList &L, int i, ElemType e){
    if(i<1 || i>(L.length+1)) return ERROR;     //i值不合法
    if(L.length == MAXSIZE) return ERROR;     //当前存储空间已满

    for(int j=L.length-1; j>=(i-1); j--){
        L.elem[j+1] = L.elem[j];    //插入位置以及之后的元素后移
    }
    L.elem[i-1] = e;   //将新元素e放入第i个位置
    L.length++;        //表长加1
    return OK;
}

//删除操作:删除第i个元素
Status ListDelete_Sq(SqList &L, int i){
    if(i<1 || i>L.length) return ERROR;   //i值不合法

    for(int j=i; j<=(L.length-1); j++){
        L.elem[j-1] = L.elem[j];   //被删除元素之后的元素前移
    }
    L.length--;   //表长减1
    return OK;
}
原文地址:https://www.cnblogs.com/CPU-Easy/p/11681919.html