【数据结构】:实现顺序表各种基本运算的算法
目的
领会顺序表存储结构和掌握顺序表中各种基本运算算法设计。
内容
编写一个程序sqlist.cpp,实现顺序表的各种基本运算和整体建表算法(假设顺序表的元素类型ElemType为char),并在此基础上设计一个主程序,完成如下功能: 初始化顺序表L 依次插入a,b,c,d,e元素 输出顺序表L 输出顺序表L长度 判断顺序表是否为空 输出顺序表L的第3个元素 输出元素a的位置 在第4个元素位置上插入f元素 输出顺序表L 删除顺序表L的第3个元素 输出顺序表L 释放顺序表L
二、详细代码
代码如下:
#include<stdio.h> #include<malloc.h> #define MaxSize 50 typedef char ElemType; typedef struct SqList { ElemType data[MaxSize]; int length; }SqList; void InitList(SqList*& L) { //初始化线性表 L = (SqList*)malloc(sizeof(SqList)); L->length = 0; } void DestroyList(SqList*& L) { //销毁线性表 free(L); } bool ListEmpty(SqList* L) { //判断线性表是否为空表 return (L->length == 0);//通过L->length判断,length为0的时候,即是空表 } int ListLength(SqList* L) { //求线性表的长度 return (L->length);//直接返回length即可 } bool GetElem(SqList* L, int i, ElemType e) { //求线性表中第i个元素值 i--; if (i<0 || i>L->length - 1) { //判断数据合法性 return false;// } else { //若合法,则输出 e = L->data[i]; return true; } } void DispList(SqList* L) { //输出线性表 for (int i = 0; i < L->length; i++) { //利用循环遍历数组,逐一输出数组元素 printf("%c", L->data[i]); } printf(" "); } int LocateElem(SqList* L, ElemType e) { //查找第一个值域为e的元素序号 for (int i = 0; i < L->length; i++) { if (e == L->data[i]) { return i+1; } } return 0; } bool InsertElem(SqList*& L, int i, ElemType e) { //插入第i个元素 int j; if (i<1 || i>L->length + 1 || L->length == MaxSize) { //对插入位置进行判断,插入位置要在表中,且表的长度与MaxSize不可相等,不然插入后数据会溢出 return false; } i--;//将i从元素位置转换成数组下标 for (j = L->length; j > i;j--) { //将插入元素后面的元素往后移动一个位置 L->data[j] = L->data[j - 1]; } L->data[i] = e; L->length++; return true; } bool ListDelete(SqList*& L, int i, ElemType e) { //删除第i个元素 int j; if (i<1 || i>L->length) { return false; } i--; e = L->data[i]; for (j = i; j < L->length - 1; j++) { L->data[j] = L->data[j + 1]; } L->length--; return true; } //到此为止,我们已经将可能用到的函数定义完毕 //下面基本只需调用以上函数即可 int main() { SqList* L; ElemType e = 0; printf("顺序表的基本运算如下"); printf("(1)初始化顺序表L "); InitList(L); printf("(2)依次插入a,b,c,d,e元素 "); InsertElem(L, 1, a); InsertElem(L, 2, b); InsertElem(L, 3, c); InsertElem(L, 4, d); InsertElem(L, 5, e); printf("(3)输出顺序表L: "); DispList(L); printf("(4)顺序表L长度:%d ",ListLength(L)); printf("(5)顺序表L为%s ", ListEmpty(L)); GetElem(L, 3, e); printf("(6)顺序表L的第3个元素:%c ",e); printf("(7)元素a的位置:%d ",LocateElem(L,a)); printf("(8)在第四给元素位置上插入f元素 "); InsertElem(L, 4, f); printf("(9)输出顺序表L: "); DispList(L); printf("(10)删除L的第3个元素 "); ListDelete(L, 3, e); printf("(11)输出顺序表L: "); DispList(L); printf("(12)释放顺序表L "); DestroyList(L); return 1; }
运行结果
如下
下一篇:
负载均衡与一致性哈希