线性表的顺序存储和链式存储(单链表)及其相关操作实现
线性表的顺序存储
顺序存储的特点
以物理位置相邻表示逻辑关系
顺序存储的优缺点
优点: 1.存储密度大(本身所占存储容量/节点结构所占存储容量) 2.可以随机存取
缺点:1.插入和删除需要移动大量元素 2.浪费空间(需要一片连续的存储空间) 3.属于自由存储形式,数据元素不能自由扩充
线性表顺序存储的代码实现及相关操作解释(C++)
#include
using namespace std;
#define TURE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXSIZE 100
typedef int Status;
typedef char ElemType;
typedef struct {
ElemType *elem;
int lenght;
}SqList;
SqList L;
Status InitList_Sq(SqList &L){//构建一个顺序表
L.elem=new ElemType[MAXSIZE];//为顺序表分配空间
if(!L.elem) exit(OVERFLOW);//存储分配失败
L.lenght=0;//空表长度;
return OK;
}
void DestoryList(SqList &L){ //销毁线性表
if(L.elem) delete L.elem;//释放存储空间
}
void ClearList(SqList &L){//清空线性表
L.lenght=0;//长度置零
}
int GetLength(SqList &L){//求线性表长度
return (L.lenght);
}
int IsEmpty(SqList &L){//判断线性表是否为空
if(L.lenght==0)return 1;
else return 0;
}
int GetElem(SqList &L,int i,ElemType &e){//取值,取线性表位置i上的元素
if(iL.lenght)return ERROR;
e=L.elem[i-1];
return OK;
}
int LocateElem(SqList &L,ElemType e){//查找e在线性表中的位置
for(int i=0;i=i-1;j--)//插入位置及后移元素
L.elem[j+1]=L.elem[j];
L.elem[i-1]=e;
L.lenght++;
return OK;
}
Status ListDelete_Sq(SqList &L,int i){
if(iL.lenght) return ERROR;
for(int j=i;j>L.elem[i]){
L.lenght++;i++;
if(cin.get()=='\n')break;
}
for(int i=0;i |