- 定义ElenType,方便更改类型(本程序采用ElemType 为int类型)
/***
*ElemType.h - ElemType的定义
*
****/
#ifndef ELEMTYPE_H
#define ELEMTYPE_H
typedef int ElemType;
#endif /* ELEMTYPE_H */
2.定义动态顺序表和基本操作
/***
*DynaSeqList.h - 动态顺序表的定义
*
****/
#if !defined(DYNASEQLIST_H)
#define DYNASEQLIST_H
#include "ElemType.h"
/*------------------------------------------------------------
// 顺序表结构的定义
------------------------------------------------------------*/
typedef struct List
{
ElemType *elem; // 存储空间的基址
int length; // 顺序表中结点元素的个数
int listsize; // 顺序表的存储空间大小
} SqList;
/*------------------------------------------------------------
// 顺序表的基本操作
------------------------------------------------------------*/
bool InitList(SqList *L); //插入
void DestroyList(SqList *L); //销毁
bool ListEmpty(SqList L); //判断表是否为空
int ListLength(SqList L); //链表长度
bool GetElem(SqList L, int i, ElemType *e); //获得第i个节点
int LocateElem(SqList L, ElemType e, int (*fp)(ElemType, ElemType));// 获得指定元素位置
bool PriorElem(SqList L, ElemType cur_e, ElemType *pre_e);
// 获得指定元素前驱
bool NextElem(SqList L, ElemType cur_e, ElemType *nxt_e);
// 获得指定元素后继
void ListTraverse(SqList L, void (*fp)(ElemType));//遍历线性表
void ClearList(SqList *L);// 清空
bool ListInsert(SqList *L, int i, ElemType e);//插入
bool ListDelete(SqList *L, int i, ElemType *e);//删除
#endif /* DYNASEQLIST_H */
3.线性表基本操作的实现
/***
*DynaSeqList.cpp - 动态顺序表,即顺序表的动态数组实现
*
*题目:实验2-1 线性表的动态顺序存储实现
*
****/
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <assert.h>
#include "DynaSeqList.h"
const int LIST_INIT_SIZE = 100; // 表初始分配的最大长度
const int LISTINCREMENT = 10; // 分配内存的增量
/*------------------------------------------------------------
操作目的: 初始化顺序表
初始条件: 无
操作结果: 构造一个空的线性表
函数参数:
SqList *L 待初始化的线性表
返回值:
bool 操作是否成功
------------------------------------------------------------*/
bool InitList(SqList *L)
{
(*L).elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!(*L).elem)
return false; /* 存储分配失败 */
(*L).length=0; /* 空表长度为0 */
(