数据结构-顺序表的实现方式

使用静态数组以及动态数组实现顺序表的一些操作

需要注意的地方:

1、两种实现方式的初始化方式

2、动态数组中,使用malloc函数时,一定要在前面进行强制转化成同一类型,这样才能保证,在进行操作的时候,每个数据元素的所占用存储空间的大小是相同的。

3、malloc函数返回的是连续存储区域的首地址。

4、插入删除操作中的特判,保证了算法的健壮性。

5、注意指针的定义方式,传参引用&(即对参数的修改结果需要带回来)

6、线性表中元素的位序是从1开始的,而数组中元素的下标是从0开始的。

静态数组

#include
#include
using namespace std;
#define MaxSize 50
#define ElemType int
typedef struct
{
    ElemType data[MaxSize];
    int length;
}SqList;

/*线性表的初始化*/
void InitList(SqList &L)
{
    for(int i=0;iL.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;
}
/*顺序表删除操作,平均时间复杂度为O(n)*/
bool ListDelete(SqList &L,int i,ElemType e)//删除在顺序表L的第i个位置,并且返回该数据元素e
{
    if(i<1||i>L.length+1)
        return false;
    e=L.data[i-1];
    for(int j=i;j

动态数组

#include
#include
#include//malloc函数需要头文件
using namespace std;
#define InitSize 10
#define ElemType int
typedef struct
{
    ElemType *data;
    int MaxSize;
    int length;
}SeqList;

void InitList(SeqList &L)
{
    L.data=(ElemType *)malloc(sizeof(ElemType)*InitSize);//动态存储的初始化方式
    L.length=0;
    L.MaxSize=InitSize;
}

/*增加动态数组的长度,加长len*/
void IncreaseSize(SeqList &L,int len)
{
    int *p=L.data;//间接存储原指针L指向的内存位置
    L.data=(ElemType *)malloc(sizeof(ElemType)*(L.MaxSize+len));
    for(int i=0;iL.length+1)
        return false;
    if(L.length>=InitSize)
        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(SeqList &L,int i,ElemType e)//删除在顺序表L的第i个位置,并且返回该数据元素e
{
    if(i<1||i>L.length+1)
        return false;
    e=L.data[i-1];
    for(int j=i;j

 

你可能感兴趣的:(数据结构)