顺序表结构:

基本方法:.h文件
1 //方法 2 Status InitList(SqList &L); //线性表L初始化(参数用引用) 3 4 void DestroyList(SqList &L); //销毁线性表L 5 6 void ClearList(SqList &L); //清空线性表L 7 8 int GetLength(SqList L); //求线性表L的长度 9 10 int IsEmpty(SqList L); //判断线性表是否为空 11 12 int GetElem(SqList L, int i, ElemType &e); //获取线性表元素 13 14 int LocateElem(SqList L, ElemType e); //获取元素的位置
方法具体定义:.cpp文件
1 #include "function_for_SqList.h"
2 //方法
3 //线性表L初始化(参数用引用)
4 Status InitList(SqList &L){ //构造一个空的顺序表
5 L.elem = new ElemType[MAXSIZE]; //为顺序表分配空间
6 if(!L.elem){
7 exit(OVERFLOW); //存储分配失败
8 }
9 L.length = 0; //空表长度为0
10 return OK;
11 }
12
13 //销毁线性表L
14 void DestroyList(SqList &L){
15 if(L.elem){
16 delete L.elem; //释放存储空间(删除此数组)
17 }
18 }
19
20 //清空线性表L
21 void ClearList(SqList &L){
22 L.length=0; //将线性表的长度置为0
23 }
24
25 //求线性表L的长度
26 int GetLength(SqList L){
27 return (L.length);
28 }
29
30 //判断线性表是否为空
31 int IsEmpty(SqList L){
32 if(L.length == 0){
33 return 1;
34 }else{
35 return 0;
36 }
37 }
38
39 //获取线性表内容:取第i个元素
40 int GetElem(SqList L, int i, ElemType &e){
41 if(i<1 || i>L.length){ //判断i值是否合理,若不合理,返回ERROR
42 return ERROR;
43 }
44 e = L.elem[i-1]; //第(i-1)个单元存储着第i个数据
45 return OK;
46 }
47
48 //查找:(顺序查找)按值查找(按给定书号进行查找,确定是否存在该图书)
49 /*
50 如果存在,输出是第几个元素
51 如果不存在,输出0
52 */
53 int LocateElem(SqList L, ElemType e){
54 for(int i=0; i<L.length; i++){
55 if(L.elem[i] == e){
56 return (i+1); //查找成功,返回序号
57 }
58 }
59 return 0; //查找失败,返回0
60 }