线性表定义:具有相同类型的n个元素的有限序列,其中n为表长,当n=0时表示空表。若用L命名线性表,则一般表示如下:
L=(a1,a2,……,an)。
线性表特点:除第一个元素外,每个元素有且仅有一个直接前驱。除最后一个元素外其余元素均有一个直接后继。
注:线性表是一种逻辑结构,而链表表示一种存储结构。
线性表具体操作:
InitList(&L) :初始化表。构造一个空表。
Length(L): 返回表长。
LocateElem(L,e):按值查找操作。在表L中查找具有给定关键字值得元素。
GetElem(L,i):按位置返回值。在表L中查找第i个位置的元素。
ListInsert(&L,i,e):插入操作。在表L中第i个位置上插入指定元素。
ListDelete(&L,i,&e):删除操作。删除表L中第i个位置的元素。并用e返回。
PrintList(L):遍历表L中的所有元素。
Empty(L):判断表L是否为空。
DestroyList(&L):销毁操作,释放线性表L所占用的内存空间。
包含所有操作文件:function.cpp
#include<malloc.h>
#include"head.h"
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXSIZE 50
Status InitList(SqList &L){//初始化链表
L.data=(ElemType*)malloc(sizeof(ElemType)*MAXSIZE);
L.Length=0;
return OK;
}
Status ListInsert(SqList &L,int i,ElemType e){//向线性表中插入元素
if(i<1||i>L.Length+1) return FALSE;//插入位置不合理
if(L.Length>=MAXSIZE) return FALSE;//线性表已满
for(int k=L.Length;k>=i;k--){
L.data[k]=L.data[k-1];
}
L.data[i-1]=e;
L.Length++;
return TRUE;
}
Status ListDelete(SqList &L,int i,ElemType &e){//删除指定位置的元素
if(i<1||i>L.Length) return FALSE;//删除位置不合理
e=L.data[i-1];
for(int k=i-1;k<L.Length;k++){
L.data[k]=L.data[k+1];
}
L.Length--;
return TRUE;
}
ElemType Length(SqList L){//返回表长
return L.Length;
}
ElemType Empty(SqList L){//判断线性表是否为空
if(L.Length>0) return FALSE;
return TRUE;
}
ElemType LocateElem(SqList L,ElemType e){//查找线性表中某个元素的位置
if(Empty(L)) return FALSE;//线性表为空
for(int k=1;k<L.Length;k++)
if(L.data[k]==e){
return k+1;
}
return FALSE;
}
ElemType GetElem(SqList L,ElemType i){//返回第i个位置元素的值
if(i<1||i>L.Length) return FALSE;//返回元素的位置不合理
return L.data[i-1];
}
ElemType DestroyList(SqList &L){//销毁链表
free(&L);
return TRUE;
}
头文件:head.h:
typedef int ElemType;
typedef int Status;
typedef struct{
ElemType *data;
ElemType Length;//表长
}SqList;
Status InitList(SqList &L);//初始化线性表
Status ListInsert(SqList &L,int i,ElemType e);//向线性表中插入元素
Status ListDelete(SqList &L,int i,ElemType &e);//删除线性表中指定位置的元素
ElemType Length(SqList L);//返回表长度
ElemType Empty(SqList L);//判断表是否为空
ElemType LocateElem(SqList L,ElemType e);//查找线性表中元素的位置
ElemType GetElem(SqList L,ElemType i);//返回第i个元素
ElemType DestroyList(SqList &L);//销毁链表
主函数:main.cpp
#include<iostream>
#include "head.h"
using namespace std;
int main(){
SqList list;
InitList(list);//初始化线性表
for(int k=1;k<11;k++)
ListInsert(list,k,k);
cout<<"返回当前线性表长度:"<<endl;
cout<<Length(list)<<endl;
cout<<"判断线性表是否为空:"<<Empty(list)<<endl;
cout<<"返回某个元素的具体位置:"<<LocateElem(list,3)<<endl;
cout<<"返回某个元素的具体位置"<<GetElem(list,4)<<endl;
DestroyList(list);
return 0;
}