【数据结构编写约定】
编写一个主程序algo2-1.cpp,用sqlist.h封装顺序表的各种算法(元素类型是char),用sqlist.cpp实现。
//Sqlist.h
#pragma once
const int MaxSize = 100;
typedef char ElemType;
typedef struct {
ElemType data[MaxSize];
int length;
} sqlist;
void InitList(sqlist*& L); // 初始化顺序表
void DestroyList(sqlist* L); // 释放顺序表
bool ListEmpty(sqlist* L); // 判断顺序表是否为空
int ListLength(sqlist* L); // 返回顺序表的长度
void PrintList(sqlist* L); // 输出顺序表
bool GetElem(sqlist* L, int i, ElemType& e); // 获取顺序表第i个元素
int LocateElem(sqlist* L, ElemType e); // 在顺序表中查找元素e
bool ListInsert(sqlist*& L, int i, ElemType e); // 在顺序表第i个位置上面插入元素e
bool ListDelete(sqlist*& L, int i, ElemType& e); // 在顺序表中删除第i个元素
//Sqlist.cpp
#include "sqlist.h"
#include
#include
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);
}
int ListLength(sqlist* L) { // 返回顺序表的长度
return L->length;
}
void PrintList(sqlist* L) { // 输出顺序表
for (int i = 0; i < L->length; ++i)
printf("%c ", L->data[i]);
printf("\n");
}
bool GetElem(sqlist* L, int i, ElemType& e) { // 获取顺序表第i个元素
if (i < 1 || i > L->length) return false; // 参数错误
e = L->data[i - 1];
return true;
}
int LocateElem(sqlist* L, ElemType e) { // 在顺序表中查找元素e
int i = 0;
while (i < L->length&& L->data[i] != e) ++i;
if (i >= L->length) return 0; // 没有找到时返回0
else return i + 1; // 找到后返回其逻辑序号(第几个)
}
bool ListInsert(sqlist*& L, int i, ElemType e) { // 在顺序表第i个位置上面插入元素e
if (i < 1 || i > L->length + 1) return false;
--i;
for (int 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个元素
if (i < 1 || i > L->length) return false;
--i;
for (int j = i; j < L->length; ++j)
L->data[j] = L->data[j + 1];
L->length--;
return true;
}
主程序中完成下面的功能:
//algo2-1.cpp
#include "Sqlist.h"
#include
#include
int main() {
sqlist *L;
ElemType e;
printf("顺序表的基本运算如下:\n");
printf(" 1. 初始化顺序表L;\n");
InitList(L);
printf(" 2. 依次采用尾插法插入a,b,c,d,e元素;\n");
ListInsert(L, 1, 'a');
ListInsert(L, 2, 'b');
ListInsert(L, 3, 'c');
ListInsert(L, 4, 'd');
ListInsert(L, 5, 'e');
printf(" 3. 输出顺序表L: \n");
PrintList(L);
printf(" 4. 输出顺序表L的长度;%d\n", ListLength(L));
printf(" 5. 判断顺序表L是否为空;%s\n", (ListEmpty(L) ? "空" : "非空"));
GetElem(L, 3, e);
printf(" 6. 输出顺序表L的第3个元素;%c\n", e);
printf(" 7. 输出元素a的位置;%d\n", LocateElem(L, 'a'));
printf(" 8. 在第4个元素位置上面插入f元素;\n");
ListInsert(L, 4, 'f');
printf(" 9. 输出顺序表L;\n");
PrintList(L);
printf(" 10. 删除L的第3个元素;\n");
ListDelete(L, 3, e);
printf(" 11. 输出顺序表L;\n");
PrintList(L);
printf(" 12. 释放顺序表\n");
DestroyList(L);
return 0;
}