C语言顺序表的构造、销毁、清空、取值、插入、删除和查询

include<stdio.h>

include<string.h>

include<malloc.h>

include<stdlib.h>

define ERROR -2

define OK 1

define OVERFLOW -1

define LIST_INIT_SIZE 100

define LISTINCREASE 10

//实现顺序表
typedef struct
{
int *elem;
int length;
int listsize;
}SqList;

//顺序表的初始化
int InitList_Sq(SqList L)
{
L->elem = (int
)malloc(sizeof(int) * LIST_INIT_SIZE);
if (!L->elem) exit(OVERFLOW);
L->length = 0;//顺序表的空间大小不代表顺序表的长度
L->listsize = LIST_INIT_SIZE;
return OK;
}

//顺序表的销除
void DestroyList(SqList *L)
{
L->length = 0;
L->listsize = 0;
free(L->elem);
L->elem = NULL;
}

//检测是否实现构造和销除功能
int main()
{
SqList p;
if (InitList_Sq(&p))
{
DestroyList(&p);
if (!(p.elem)) ("销毁成功");
}
}

//顺序表的清空
void ClearList(SqList *L)
{
if (!L->elem) exit(OVERFLOW);//清空表的的前提是表要存在
//顺序表的清空代表着表里面没有任何元素,但其本身的所申请的空间仍然还存在,所以只需将顺序表的长度设为0即可
L->length = 0;
}

//检测表有没有清空
int main()
{
SqList p;
if (InitList_Sq(&p))
{
DestroyList(&p);
ClearList(&p);
printf("%d", p.length);
}
}

//判断顺序表是否为空表
bool ListEmpty(SqList L)//查询操作不会改变顺序表,所以形参不需要用指针
{
if (!L.elem) exit(OVERFLOW);//判断表为空的前提是表要存在
if (L.length == 0) return OK;
else return 0;
}

//计算顺序表的长度
int ListLength(SqList L)
{
if (!L.elem) exit(OVERFLOW);//计算表的长度的前提是表要存在
return L.length;
}

//向顺序表中插入数据
int ListInsert(SqList L, int i, int e)//在第i个位置之前插入一个数据,i >= 1
{
if (!L->elem) exit(OVERFLOW);//向表中插入数据的前提是表要存在
if (i < 1 || i > L->length + 1)//i的范围是顺序表第一个元素之前和最后一个元素的下一个元素之前
return ERROR;
if (L->length == L->listsize)//插入之前应该判断顺序表是否已满,如果满了,就需要重新申请一块更大的内存
{
L->elem = (int
)malloc(sizeof(int) * (L->listsize + LISTINCREASE));
if (!L->elem) exit(OVERFLOW);
L->listsize += LISTINCREASE;
}
for (int j = L->length - 1; j >= i - 1; j--)
{
L->elem[j + 1] = L->elem[j];
}
L->elem[i - 1] = e;
L->length++;
}

//检测表的长度是否计算正确以及插入元素是否正确
int main()
{
SqList p;
InitList_Sq(&p);
ListInsert(&p, 1, 1);
ListInsert(&p, 1, 2);
int len = ListLength(p);
printf("%d %d %d", p.elem[0], p.elem[1], len);
}

//从数据表中删除数据
int ListDelete(SqList *L, int i)//删除第i个位置的元素
{
if (!L->elem) exit(OVERFLOW);//从表中删除数据的前提是表要存在
if (L->length == 0) return ERROR;//在删除元素之前需要检查表中是否有元素可删
if (i < 1 || i > L->length) return ERROR;//i的范围应该是第一个元素到最后一个元素的位置
int e = L->elem[i - 1];
for (int j = i - 1; j < L->length - 1; j++)
{
L->elem[j] = L->elem[j + 1];
}
L->length--;
return e;
}

//检测是否正确删除数据
int main()
{
SqList p;
InitList_Sq(&p);
ListInsert(&p, 1, 1);
ListInsert(&p, 1, 2);
int len = ListLength(p);
printf("%d %d %d\n", p.elem[0], p.elem[1], len);
printf("%d\n",ListDelete(&p, 1));
for (int j = 0; j < p.length; j++)
printf("%d\n", p.elem[j]);
}

//查找数据元素i是否在顺序表里,如果在,返回i的位置,如果不在,返回ERROR
int LocateElem(SqList L, int i)
{
int j, flag = 0;//找到了flag为1,没找到为0
if (!L.elem) exit(OVERFLOW);
for (j = 0; j < L.length; j++)
{
if (L.elem[j] == i)
{
flag = 1;
break;
}
}
if (!flag) return ERROR;
else return j + 1;
}

//查询第i个位置上的元素
int GetElem(SqList L, int i)
{
if (!L.elem) exit(OVERFLOW);
if (i < 1 || i > L.length) return ERROR;
return L.elem[i - 1];
}

上一篇:数据结构


下一篇:C++小白学习笔记——代码案例(3)