当前位置:文档之家› 数据结构实验2.1顺序表

数据结构实验2.1顺序表

数据结构实验2.1顺序表
数据结构实验2.1顺序表

附页(实验2-1代码):

头文件“DEFINE2-1.h”:

#define MaxSize 10

typedef struct

{

char data[MaxSize];

int length;

}SqList;

#include

#include

#include"DEFINE2-1.h"

void InitList(SqList * &L) //初始化线性表

{

L = (SqList*)malloc(sizeof(SqList)); //分配存放线性表的空间L->length = 0; //置空线性表长度为0

}

bool ListInsert(SqList *&L, int i, char e) //插入数据元素

{

int j;

if (i<1 || i>L->length + 1)

return false; //参数错误是返回false I--; //将顺序表逻辑序号转换为物理序号for (j = L->length; j>i; j--) //将data[i]及后面元素后移一个位置L->data[j] = L->data[j - 1];

L->data[i] = e; //插入元素e

L->length++; //顺序表长度+1

return true; //成功插入返回true

}

void DispList(SqList *L) //输出线性表L

{

int i;

for (i = 0; ilength; i++) //扫描顺序表输出各元素值printf("%3c", L->data[i]);

printf("\n\n");

}

int ListLength(SqList *L) //求线性表L的长度

{

return (L->length);

}

bool ListEmpty(SqList*L) //判断线性表是否为空表

{

return(L->length == 0); //若L为空,则返回true,否则返回false

}

bool GetElem(SqList *L, int i, char &e) //求顺序表L中某个数据元素值{

if (i<1 || i>L->length)

return false; //参数错误时返回false

e = L->data[i - 1]; //取元素值

return true; //成功找到元素时返回true

}

int LocateElem(SqList *L, char e) //按元素值查找

{

int i = 0;

while (ilength&&L->data[i] != e)

i++; //查找元素e

if (i >= L->length)

return 0; //未找到时返回0

else

return i + 1; //找到时返回其逻辑序号

}

bool ListDelete(SqList *&L, int i, char &e) //删除数据元素

{

int j;

if (i<1 || i>L->length)

return false; //参数错误时返回false i--; //将顺序表逻辑序号转化为物理序号

e = L->data[i];

for (j = i; jlength - 1; j++)

L->data[j] = L->data[j + 1]; //将data[i]之后的元素迁移一个位置L->length--; //顺序表的长度-1

return true; //成功删除返回true

}

void DestroyList(SqList * &L) //销毁线性表

{

free(L);

} //释放线性表L所占空间

int main() //主函数

{

SqList *L;

char e;

int i;

InitList(L);

printf("\n创建一个空的线性表\n使用尾插法插入a,b,c,d,e \n");

printf(" 输出顺序表L: \n");

ListInsert(L, 1, 'a');

ListInsert(L, 2, 'b');

ListInsert(L, 3, 'c');

ListInsert(L, 4, 'd');

ListInsert(L, 5, 'e');

DispList(L);

ListLength(L);

printf("顺序表的长度为:%d\n\n", L->length);

if (ListEmpty(L) == 1)

printf("顺序表为空!\n\n");

else

printf("顺序表不为空!\n\n");

GetElem(L, 3, e);

printf("顺序表的第三个元素为:%3c\n\n", e);

i = LocateElem(L, 'a');

printf("顺序表中a的位置是:%3d\n\n", i);

ListInsert(L, 4, 'f');

printf("在第四个元素位置上插入元素'f' \n");

printf(" 插入后顺序表L为:\n");

DispList(L);

printf("删除L中第三个元素\n");

ListDelete(L, 3, e);

printf(" 删除后顺序表L为:\n");

DispList(L);

printf("顺序表L已释放\n");

DestroyList(L);

printf("\n");

return 0;

}

实验结果:

相关主题
文本预览
相关文档 最新文档