数据结构学习笔记
线性表
定义 n个数据元素的有限序列
(这学期接触了数据结构这一课程,本以为C语言顶多只需要造一下轮子就行了,可是这通篇的伪代码告诉我还得自己种橡胶树)
今天就先来种一下橡胶树吧,因为引用数据类型.c跑不了,所以上.cpp了
废话不多说,直接种树吧
day 01
#include <stdio.h>
using namespace std;
#define TRUE 1
#define FAlSE 0
#define OK 1
#define ERROR 0
#define INFEASINBLE -1
#define OVERFLOW -2
#define LIST_INIT_SIZE 100 //线性表可达最大长度
#define MAXSIZE 100
#define LISTINCREMENT 10
typedef int Status; //Status是函数类型,其值是函数结果状态代码
typedef struct
{
ElemType *elem; //线性表储存空间基址,其储存空间在建立空表时动态分配
int length; //当前线性表长度
int listSize;
}SqList;
Status InitList(SqList &L)
{//构建一个空的顺序表L
// L.elem = new ElemType[MAXSIZE]; //为顺序表分配一个大小为MAXSIZE的数组空间
L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!L.elem) exit(OVERFLOW); //储存分配失败退出
L.length = 0; //空表长度为0
L.listSize = LIST_INIT_SIZE;
return OK;
}
void DestroyList(SqList &L)
{//销毁线性表L
// if(L.elem) delete[]L.elem; //释放储存空间
delete(L.elem);
L.elem = NULL;
L.length = 0;
L.listSize = 0;
return OK;
}
void ClearList(SqList &L)
{//清空线性表将L置为空表
L.length = 0;
return OK;
}
Status ListEmpty(SqList L)
{//判断线性表是否为空
if (L.length == 0) return TRUE;
else return FAlSE;
}
Status ListLength(SqList L)
{//返回L中数据元素个数
return (L.length);
}
Status GetElem(SqList L, int i, ElemType &e)
{//用e返回L中第i个元素的值
if (i<1 || i>L.length) exit(ERROR);
e = *(L.elem + i - 1);
return OK;
}
Status LocateElem(SqList l, ElemType e, Status (*compare)(ElemType,ElemType))
{//返回L中第1个与e满足compare()关系的数据元素的位序
int i = 1;
ElemType *p = L.elem;
while(i<=L.length && !(*compare)(*p++, e)) ++i;
if (i<=L.length) return i;
else return FAlSE;
}
Status PriorElem(SqList L, ElemType cur_e, ElemType &pre_e)
{//若cur_e是L的数据元素,且不是第一个,则用pre_e返回它的前驱,否则操作失败,pre_e无定义
int i = 2;
ElemType *p = L.elem + 1;
while (i<=L.length && *p != cur_e);
{
p++;
i++;
}
if (i>L.length) return INFEASINBLE;
pre_e = *(-p);
return OK;
}
Status NextElem(SqList L, ElemType cur_e, ElemType next_e)
{//若cur_e是L的数据元素,且不是第一个,则用next_e返回它的前驱,否则操作失败,next_e无定义
int i = 1;
ElemType *p = L.elem;
while(i<length && *p != e)
{
i++;
p++;
}
if (i==L.length) return INFEASINBLE;
next_e = *(++p);
return OK;
}
Status ListInsert(SqList &L, int i, ElemType e)
{//在L中第i个位置之前插入一个新的数据元素e,L的长度+1
if (i<1 || i>L.length+1) return ERROR; //i的值不合法
if (L.length>=L.listSize)
{
ElemType *newbase = (ElemType)realloc(L.elem,(L.listSize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase) return ERROR;
L.elem = newbase;
L.listSize += LISTINCREMENT;
}
for (int j=L.length-1; j>=i-1; j++) L.elem[i-1] = L.elem[j];
L.elem[i-1] = e;
L.length++;
return OK;
}
Status ListDelete(SqList &L, int i, ElemType &e)
{//删除L中的第i个元素,并用e返回其值,长度-1
if (i<1 || i>L.length) return ERROR;
e = L.elem[i-1];
for (int j=i-1;i<1 || i>L.length-1; j++) L.elem[j] = L.elem[j+1];
L.length --;
return OK;
}
Status ListTrverse(SqList L, void (*visit)(ElemType*))
{//依次对L中每个数据元素调用函数visit(),一旦visit()失败,则操作失败
ElemType *p = L.elem;
for (int i=1; i<=L.length;i++) visit(p++);
printf("\n");
return OK;
}
后面有空会持续更新…欢迎继续关注