线性表

本文最后更新于 2025年8月25日 晚上

线性表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
ADT LinearList{
数据对象:D={aⁱ|aⁱ∈D₀,i=1,2,...,n,n≥0,D₀为某一数据对象}
结构关系:R={<aⁱ,aⁱ+1>|aⁱ,aⁱ+1∈D,i=1,2,...,n-1}
基本操作:
1.InitList(L)
操作前提:L为未初始化线性表。
操作结果:将L初始化为空表。
2.ListLength(L)
操作前提:线性表L已存在。
操作结果:如果L为空表则返回0,否则返回表中的元素的个数。
3.GetData(L,i)
操作前提:表L存在,且1≤i≤ListLength(L)。
操作结果:返回线性表L中第i个合法元素的值。
4.InsList(L,i,e)
操作前提:表L已存在,e为合法元素值且1≤i≤ListLength(L)+1
操作结果:在L中第i个位置之前插入新的数据元素e,L的长度加1
5.DelList(L,i,e)
操作前提:表L已存在且非空,1≤i≤ListLength(L)。
操作结果:删除L的第i个数据元素,并用e返回其值,L的长度减1
6.Locate(L,e)
操作前提:表L已存在,e为合法数据元素值。
操作结果:如果L中存在数据元素e,则返回e在L中的位置,否则返回空位置。
7.DestroyList(L)
操作前提:线性表已存在。
操作结果:将L销毁。
8.ClearList(L)
操作前提:线性表L已存在。
操作结果:将L置为空表。
9.EmptyList(L)
操作前提:线性表L已存在。
操作结果:如果L为空表则返回TRUE,否则返回FALSE。
}ADT LinearList;

结构体

1
2
3
4
5
6
7
8
9
10
11
#define MAXSIZE 100

typedef struct {
int * elem;
int length;
} SqList;

typedef enum {
OK = 1,
ERROR = 0
}Status;

image-20250809151136403.png

image-20250809151425453.png

初始化线性表

1
2
3
4
5
6
Status InitList(SqList *sqList){
sqList->elem = malloc(sizeof(int) * MAXSIZE);
if(sqList->elem == NULL) return ERROR;
sqList->length = 0;
return OK;
}

销毁线性表

1
2
3
void DestroyList(SqList *sqList){
if(sqList) free(sqList);
}

清空线性表

1
2
3
void ClearList(SqList *sqList){
sqList->length = 0;
}

线性表的长度

1
2
3
int GetLength(SqList *sqList){
return sqList->length;
}

判断线性表是否为空

1
2
3
4
Status IsEmptyList(SqList *sqList){
if(!sqList->length) return OK;
else return ERROR;
}

线性表取值

1
2
3
4
5
Status GetElem(SqList *sqList,int i,int *elem){
if(i < 1 || i>sqList->length) return ERROR;
*elem = sqList->elem[i-1];
return OK;
}

顺序表的查找

1
2
3
4
5
6
int LocateElem(SqList *sqList,int i,int elem){
for (int j = 0; j < sqList->length; ++j) {
if(sqList->elem[j] == elem) return j + 1;
}
return 0;
}

线性表插值

1
2
3
4
5
6
7
8
9
Status InsertList(SqList *sqList,int i,int elem){
if(i < 1 || i > sqList->length + 1 || sqList -> length == MAXSIZE) return ERROR;
for (int j = sqList->length; j > i-1; --j) {
sqList->elem[j] = sqList->elem[j-1];
}
sqList->elem[i-1] = elem;
sqList->length ++;
return OK;
}

线性表删除

1
2
3
4
5
6
7
8
Status DeleteList(SqList *sqList,int i){
if(i < 1 || i > sqList->length) return ERROR;
for (int j = i; j <= sqList->length; j++) {
sqList->elem[j-1] = sqList->elem[j];
}
sqList->length --;
return OK;
}

线性表打印

1
2
3
4
5
void PrintList(SqList *sqList){
for (int j = 0; j < sqList->length; j++) {
printf_s("第%d个元素的值为:%d\n",j+1,sqList->elem[j]);
}
}

main函数

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(void) {
SqList sqList ={};
Status status = InitList(&sqList);
printf_s("创建线性表%d\n",status);

InsertList(&sqList,1,5);
InsertList(&sqList,2,6);
InsertList(&sqList,3,7);

PrintList(&sqList);

return 0;
}

本文作者: zhangJinLong
本文链接: https://zhang426fly.github.io/2025/08/09/data_structure/linear_list/
版权声明: 本博客所有文章除特别声明外,均采用BY-NC-SA许可协议。转载请注明出处!


线性表
https://zhang426fly.github.io/2025/08/09/data_structure/linear_list/
作者
zhangJinLong
发布于
2025年8月9日
许可协议