可以说顺序表是最简单,最容易学习的数据结构,基本操作代码如下:
#include <iostream>
#include <stdlib.h>
using namespace std;
/**
* 线性表的顺序存储表示(顺序表 Sequential list)
* 参考书籍:《数据结构(C语言版)第二版》严蔚敏 李冬梅 吴伟民 人民邮电出版社
* 作者: smileyan (qq837764072)
* 时间: 2018/7/2
*/
// 宏定义
#define OK 1
#define ERROR 0
#define OVERFLOW -2
// 定义数据类型
typedef int Status;
typedef int ElemType;
// 定义结构体
#define MAXSIZE 100
typedef struct
{
ElemType *elem; // 存储空间的基地址
int length; // 当前长度
}SqList; // 顺序表的结构类型
// 初始化
Status InitList(SqList& L)
{
L.elem = new ElemType[MAXSIZE];
if(!L.elem) exit(OVERFLOW);
L.length=0;
return OK;
}
// 取值 返回第i个元素(i>0)
Status GetElem(SqList L,int i,ElemType& e)
{
if(i<1 || i>L.length) return ERROR;
e = L.elem[i-1];
return OK;
}
// 查找 返回与e相等的第一个元素的位置i (i>0) 不存在则返回0
int LocateElem(SqList L,ElemType e)
{
for(int i=0; i<L.length; i++)
{
if(L.elem[i]==e) return i+1;
}
return 0;
}
// 将元素e插入到第i个位置
Status ListInsert(SqList& L,int i, ElemType e)
{
if(i<1||i>L.length+1) return ERROR;
if(L.length==MAXSIZE) return ERROR;
// 插入数据,后面的内容全部后移
for(int j=L.length-1; j>=i-1; j--)
{
L.elem[j+1]=L.elem[j];
}
// 赋值
L.elem[i-1]=e;
++L.length;
return OK;
}
// 删除第i个元素
Status ListDelete(SqList& L,int i)
{
if(i<1||i>L.length) return ERROR;
for(int j=i; j<=L.length-1; j++)
{
L.elem[j-1]=L.elem[j];
}
--L.length;
return OK;
}
// 回收内存
Status DestroyList(SqList& L)
{
delete L.elem;
return OK;
}
int main()
{
// 定义并初始化
SqList list;
InitList(list);
ListInsert(list,1,4);
int e;
GetElem(list,1,e);
cout<<e<<endl;
DestroyList(list);
return 0;
}