04 顺序存储的线性表 及线性表操作方法定义

线性表结构:

 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 }
61 
62 //插入操作:将元素e插在第i个位置上
63 Status ListInsert_Sq(SqList &L, int i, ElemType e){
64     if(i<1 || i>(length+1)) return ERROR;     //i值不合法
65     if(L.length == MAXSIZE) return ERROR;     //当前存储空间已满
66 
67     for(int j=length-1; j>=(i-1); j--){
68         L.elem[j+1] = L.elem[j];    //插入位置以及之后的元素后移
69     }
70     L.elem[i-1] = e;   //将新元素e放入第i个位置
71     L.length++;        //表长加1
72     return OK;
73 }
74 
75 //删除操作:删除第i个元素
76 Status ListDelete_Sq(SqList &L, int i){
77     if(i<1 || i>L.length) return ERROR;   //i值不合法
78 
79     for(int j=i; j<=(L.length-1); j++){
80         L.elem[j-1] = L.elem[j];   //被删除元素之后的元素前移
81     }
82     L.length--;   //表长减1
83     return OK;
84 }

猜你喜欢

转载自www.cnblogs.com/CPU-Easy/p/11681919.html