数据结构:线性表
线性表:List,
栈存储,空间小
(1)结点中只有自身的信息域,没有关联信息域。
因此,顺序存储结构的存储密度大、存储空间利用率高。
(2)通过计算地址直接访问任何数据元素,即可以随机访问。
(3)插入和删除操作会引起大量元素的移动。
头文件
/*
线性表学习-tiansch
2022-05-21
*/
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 200
typedef int Status;
typedef int ElemType;
//静态分配
//顺序存储线性表
typedef struct SqList
{
ElemType data[MAXSIZE];
int Length;
};
//基本方法:
//初始化顺序线性表
Status InitList(SqList *L);
//判断是否为空表
bool ListEmpty(SqList L);
//清空顺序线性表
void ClearList(SqList *L);
//获取顺序线性表L中第i个元素,存入*e
Status GetElem(SqList L,int i,ElemType *e);
//顺序线性表中查找与e相等的元素,返回序号
int LocateElem(SqList L,ElemType e);
//顺序线性表L中第i个位置插入e
Status ListInsert(SqList *L,int i,ElemType e);
//删除顺序线性表L中第i个位置元素,存入*e
Status ListDelete(SqList *L,int i,ElemType *e);
//返回顺序线性表L长度
int ListLength(SqList L);
实现
/*
线性表学习-tiansch
2022-05-21
*/
#include "List_Learn.h"
//初始化顺序线性表
Status InitList(SqList *L)
{
L->data[0] = 0;
L->Length=0;
return OK;
}
/*
函数名:GetElem
参数:线性表L,序号i,返回元素到e
初始条件:线性表L已经存在,1<=i<=ListLength(L)
操作结果:用e返回L中第i个元素的值
*/
Status GetElem(SqList L,int i,ElemType *e)
{
if (L.Length==0 || i<1 || i>L.Length) //线性表为空,或者i不在范围内
{
return ERROR;
}
*e=L.data[i-1];
return OK;
}
/*
函数名:ListInsert
参数:线性表L,序号i,元素e
初始条件:线性表L存在,1<=i<=ListLength(L)
操作结果:在L中第i个位置之前插入新的元素e,L长度+1
*/
Status ListInsert(SqList *L,int i,ElemType e)
{
int k;
if (L->Length == MAXSIZE) // 线性表满了
{
return ERROR;
}
if (i<1 || i>L->Length+1) //i不在范围内
{
return ERROR;
}
if (i<=L->Length) //插入数据不在表尾
{
for (k=L->Length-1;k>=i-1;k--) //Length 永远比数组的索引大1
{
L->data[k+1] = L->data[k];
}
}
L->data[i-1] = e;
L->Length++;
return OK;
}
/*
函数名:ListDelete
参数:线性表L,序号i,元素e
初始条件:线性表L存在,1<=i<=ListLength(L)
操作结果://删除L中第i个位置元素,L长度-1,用e返回其值
*/
Status ListDelete(SqList *L,int i,ElemType *e)
{
int k;
if (L->Length==0 || i<1 || i>L->Length) //线性表为空,或者i不在范围内
{
return ERROR;
}
*e = L->data[i-1];
if (i<L->Length) //删除数据不在表尾
{
for (k=i;k<L->Length;k++) //Length 永远比数组的索引大1
{
L->data[k-1] = L->data[k];
}
}
L->Length--;
return OK;
}
//返回线性表L长度
int ListLength(SqList L)
{
int iLength = L.Length;
return iLength;
}
//链表中查找与e相等的元素,返回序号
int LocateElem(SqList L,ElemType e)
{
if (L.Length==0 ) //线性表为空,或者i不在范围内
{
return ERROR;
}
for (int i = 0; i < L.Length; i++)
{
if (e = L.data[i])
{
return i+1;
}
}
return ERROR;
}
//清空顺序线性表
void ClearList(SqList *L)
{
L->Length = 0;
}
//判断是否为空表
bool ListEmpty(SqList L)
{
if (L.Length ==0 )
{
return OK;
}
return ERROR;
}