线性表(数组实现)代码记录

#include 
#include  //添加malloc函数的头文件
#include 

/*
    InitList(&L):初始化表。构造一个空的线性表。
    Length(L):求表长。返回线性表L的长度,即L中元素的个数。
    LocateElem(L,e):按值查找操作。在表L中查找具有给定关键字值的元素。
    GetElem(L,e):按位查找操作。获取表L中第i个位置的元素的值。
    ListInsert(&L, i, e):插入操作。在表L中第i个位置上插入指定元素e。
    ListDelete(&L, i , &e):删除操作。删除表L中第i个位置的元素,并用e返回删除元素的值。
    PrintList(L):输出操作。按前后顺序输出线性表L的所有元素值。
    Empty(L):判空操作。若L表为空,则返回true,否则返回false。
    DestoryList(&L):销毁操作。销毁线性表,并释放线性表L所占用的内存空间。
*/

using namespace std;

#define LIST_INIT_SIZE 100
typedef int ElemType;
typedef struct{
    ElemType* data;
    int length;
    int MaxSize;
}SeqList;

/*初始化线性表*/
bool InitList(SeqList &L)
{
    L.data = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
    L.length = 0;
    L.MaxSize = LIST_INIT_SIZE;
    return true;
}

/*线性表的长度*/
int Length(SeqList L)
{
    return L.length;
}

/*按值查找操作。在表L中查找具有给定关键字值的元素。*/
int LocateElem(SeqList L, ElemType e)
{
    int i;
    for(i=0; iL.length)
    {
        cout<<"i不在合法的范围内"<L.length+1)
    {
        return false;
    }
    if(L.length > L.MaxSize)
    {
        return false;
    }
    for(int j=L.length-1; j>=i; j--)
    {
        L.data[j] = L.data[j-1];
    }
    L.data[i-1] = e;
    L.length++;
    return true;
}

/*ListDelete(&L, i , &e):删除操作。删除表L中第i个位置的元素,并用e返回删除元素的值。*/
bool ListDelete(SeqList &L, int i, ElemType &e)
{
    if(i<1 || i>L.length)
    {
        return false;
    }
    e = L.data[i-1];
    for(int j=i; j

 

你可能感兴趣的:(DataStructure)