#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define INITSIZE 100
typedef int Status;
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
int listsize;
} SqList;
//构造线性表
Status InitList(SqList *L) {
L->elem = (ElemType*) malloc(sizeof(ElemType) * INITSIZE);
if (!L->elem)
exit(OVERFLOW);
L->length = 0;
L->listsize = INITSIZE;
return OK;
}
//销毁线性表
Status DestroyList(SqList *L) {
free(L->elem);
L->elem = NULL;
L->length = 0;
L->listsize = 0;
return OK;
}
//重置线性表
Status ClearList(SqList *L) {
free(L->elem);
L->elem = (ElemType*) malloc(INITSIZE * sizeof(ElemType));
if (!L->elem)
exit(OVERFLOW);
L->length = 0;
L->listsize = INITSIZE;
return OK;
}
//判断线性表是否为空表
Status EmptyList(SqList L) {
return L.length == 0 ? TRUE : FALSE;
}
//线性表的长度
Status ListLength(SqList L) {
return L.length;
}
//返回值
Status GetElem(SqList L, int i) {
if (i < 1 || i > L.length)
return ERROR;
return L.elem[i - 1];
}
//判断元素
Status LocateElem(SqList L, ElemType e) {
for (int i = 0; i < L.length; i++) {
if (L.elem[i] == e)
return i + 1;
}
return ERROR;
}
//序偶关系
//前驱
Status PreElem(SqList L, int i) {
if (i <= 1 || i > L.length)
return ERROR;
return L.elem[i - 2];
}
//后继
Status NextElem(SqList L, int i) {
if (i < 1 || i >= L.length)
return ERROR;
return L.elem[i];
}
//插入(前插入):在第i个元素处插入,有L->length-i+1个元素后移
Status ListInsert(SqList *L, int i, ElemType e) {
if (i < 1 || i > L->length + 1)
return ERROR;
for (int j = L->length; j >= i; j--) {
L->elem[j] = L->elem[j - 1];
}
L->elem[i - 1] = e;
// 线性表长度加一
L->length++;
return OK;
}
//删除元素:删除第i个元素,有L->length-i个元素前移
Status ListDetele(SqList *L, int i) {
if (i < 1 || i > L->length)
return ERROR;
ElemType e = L->elem[i - 1];
for (int j = L->length - i; j > 0; j--) {
L->elem[L->length - j - 1] = L->elem[L->length - j];
}
L->length--;
return e;
}
//打印
Status ListPrint(SqList L) {
for (int i = 1; i <= L.length; i++) {
printf("%d\n", GetElem(L, i));
}
return OK;
}
//主函数
int main(void) {
SqList L;
// 初始化线性表
InitList(&L);
// 0
printf("%d\n", ListLength(L));
// TRUE
printf("%d\n", EmptyList(L));
// 插入操作
ListInsert(&L, 1, 20);
ListInsert(&L, 1, 19);
ListInsert(&L, 1, 18);
ListInsert(&L, 1, 17);
ListInsert(&L, 1, 16);
// 5
printf("%d\n", ListLength(L));
// FALSE
printf("%d\n", EmptyList(L));
// 返回值
int a = GetElem(L, 3);
printf("%d\n", a);
// 判断值,返回在线性表的位置
printf("%d\n", LocateElem(L, 20));
// ERROR
printf("%d\n", LocateElem(L, 15));
// 前驱后继:18的前驱17后继19
printf("%d\t%d\n", PreElem(L, 3), NextElem(L, 3));
// 删除元素:返回被删除的元素
printf("%d\n", ListDetele(&L, 3));
// 打印
ListPrint(L);
// 清空:返回OK
printf("%d\n", ClearList(&L));
// 销毁线性表:返回OK
printf("%d\n", DestroyList(&L));
return 0;
}
数据结构线性表C语言实现
最新推荐文章于 2024-07-23 12:29:02 发布