数据结构顺序表初始化、获取长度、增、删、查

#include<iostream>
#define MaxSize 50
#define ElemType int
using namespace std;

//typedef struct{
//    ElemType data[MaxSize];
//    int length;
//}SqList1;

typedef struct{
    ElemType *data;
    int length;
}SqList2;
//初始化线性表
bool InitList(SqList2 &L)
{
    L.data = new ElemType[MaxSize];
    if(!L.data)
        return false;
    L.length = 0;
    return true;
}
//求表的长度,返回表的长度
int getLength(SqList2 L)
{
    return L.length;
}
//按值查找一个元素在线性表中的位置,location为元素位置
int LocateELem(SqList2 L,ElemType e)
{
    int location;
    for(int i=0;i<L.length;i++)
    {
        if(L.data[i] == e)
        {
            location = i+1;
            break;
        }
    }
    return location;
}
//按位查找。获取表在第i个位置的元素
ElemType GetElem(SqList2 L,int location)
{
    ElemType e;
    e = L.data[location-1];
    return e;
}
//输出操作,按照前后顺序输出线性表中所有元素
void PrintList(SqList2 L)
{
    if(L.length == 0) cout << "空打印(线性表已空)";
    for(int i=0;i<L.length;i++)
    {
        cout << L.data[i] << " ";
    }
    cout << endl;
}
//插入操作:在表中第i个位置插入指定元素
bool ListInsert(SqList2 &L,ElemType e,int location)
{
    if(location > L.length+1 || location < 1)
    {
        cout << "location越界" << endl;
        return false;
    }
    for(int i=L.length;i>=location;i--)
        L.data[i] = L.data[i-1];
    L.data[location-1] = e;
    L.length++;
    return true;
}
//删除操作:删除表中第i个位置的元素
bool ListDelete(SqList2 &L,int location)
{
    if(L.length == 0)
    {
        cout << "顺序表已空" << endl;
        return false;
    }

    if(location > L.length || location < 1)
    {
        cout << "location越界" << endl;
        return false;
    }
    for(int i=location-1;i<L.length;i++)
    {
        L.data[i] = L.data[i+1];
    }
    L.length--;
    return true;
}

//判空操作,若L为空,则返回true
bool Empty(SqList2 L)
{
    if(L.length == 0)
        return true;
    return false;
}
//销毁操作。销毁线性表,并释放线性表L所占内存空间
void DestoryList(SqList2 &L)
{
    delete[] L.data;
    L.length = 0;
}
int main()
{
    SqList2 L;
    InitList(L);
    int length = getLength(L);
    cout << length << endl;
    for(int i=0;i<5;i++)
    {
        L.data[i] = i+1;
        L.length++;
    }
    length = getLength(L);
    cout << length << endl;
    PrintList(L);
    ListInsert(L,0,6);
    PrintList(L);
    ListDelete(L,1);
    PrintList(L);
    DestoryList(L);
    PrintList(L);
}

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页