#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>//malloc函数和free函数的头文件
typedef struct Stu {
char name[20];
int num;
}ElemType;//定义一个Stu类型,重定义为ElemType类型
//顺序表的动态定义
typedef struct SeqList {
ElemType* data; //指示动态分配数组的指针
int MaxSize; //当前分配的最大容量
int length; //当前个数
}SeqList; //动态分配数组顺序表的类型定义
//注意:动态分配需要搭配malloc(申请)函数和free(释放)函数进行使用;
//L.data == (ElemType*)malloc(sizeof(ElemType) * InitSize);
//ElemType* 指的是进行强制类型转换,因为不知道申请的空间的类型是什么;
//sizeof(ElemType)指的是判断一个数据类型的空间大小是多少;
//InitSize 指的是申请的空间的个数,同时它也是malloc函数的参数
//sizeof(ElemType) * InitSize——指明申请的空间有多少,每个空间多大
//初始化表(动态分配)—创建一个空的顺序表
//先申请空间,然后对线性表进行初始化——即将顺序表的长度置为0;
void InitList(SeqList* L) {
L->data = (ElemType*)malloc(sizeof(ElemType) * 5);
L->length = 0;
L->MaxSize = 5;
}
//增加动态数组的长度
void IncreaseSize(SeqList* L, int len) {
ElemType* p = L->data;
L->data = (ElemType*)malloc(sizeof(ElemType) * (L->MaxSize + static_cast<unsigned long long>(len)));
if (L->data == NULL) {
printf("内存分配不成功!\n");
}
else {
for (int i = 0; i < L->length; i++) {
L->data[i] = p[i];
}
}
L->MaxSize = L->MaxSize + len;
free(p);
}
//对顺序表求表长
int Length(SeqList L) {
return L.length;
}
//按值查找操作,在表L中查找具有给定关键字值的元素e,并返回其位序
int LocateElem(SeqList L, ElemType e) {
int i = 0;
while (i<L.length) {
if (L.data[i].name != e.name && L.data[i].num != e.num) {
i++;
}
else {
return i+1;
}
}
return 0;
}
//按位查找操作,获取表L中第i个位置的元素的值
ElemType GetElem(SeqList L, int i) {
if (i > L.length) {
printf("查找的值非法");
}
else {
return L.data[i-1];
}
}
//插入操作—在表L中的第i个位置上插入指定的元素e
bool ListInsert(SeqList* L, int i, ElemType e) {
if (L->length == L->MaxSize) {
IncreaseSize(L, 1);
L->MaxSize = L->MaxSize + 1;
}
if (i < 1||i > L->length + 1) {
return false;
}
for (int j = L->length; j > i; j--) {
L->data[j] = L->data[j - 1];
}
L->data[i-1] = e;
L->length++;
return true;
}
//删除操作—删除表L中的第i个位置上的元素,并用e返回删除元素的值;
bool ListDelete(SeqList* L, int i, ElemType* e) {
if (i < 1 || i > L->length + 1) {
return false;
}
*e = L->data[i - 1];
for (int j = i; j < L->length; j++) {
L->data[j-1] = L->data[j];
}
L->length--;
return true;
}
//输出操作—按照前后顺序依次输出线性表L中的所有的元素的值
void PrintList(SeqList L) {
for (int i = 0; i < L.length; i++) {
printf("%s", L.data[i].name);
printf("\t");
printf("%d\n", L.data[i].num);
}
}
//判空操作—若L为空表则返回true,否则返回flase;
bool Empty(SeqList L) {
if (L.length == 0) {
return true;
}
else {
return false;
}
}
//销毁操作—销毁顺序表,并释放顺序表L所占用的空间
void DestroyList(SeqList* L) {
free(L);
}
int main() {
SeqList L;
InitList(&L);
ElemType elem ;
ElemType elem1 = { "er",00002 };
ElemType e[5] = { {"yi",00001},{ "er",00002 },{"san",00003 },{ "si",00004 },{ "wu",00005 } };
for (int i = 0; i < 5; i++) {
ListInsert(&L, i + 1, e[i]);
}
ListDelete(&L, 3, &elem);
PrintList(L);
printf("\n%s\t%d\n", elem.name, elem.num);
int x=ListInsert(&L, 2, elem1);
printf("%d\n", x);
ElemType elem2 = GetElem(L, 2);
printf("%s\t%d\n", elem2.name, elem2.num);
DestroyList(&L);
return 0;
}
线性表——顺序表的各项函数
最新推荐文章于 2024-07-19 19:11:19 发布