手写了一波C++顺序表,加深理解。
最大感触:创建一个数组对象,指定数组长度(自定义创建参数length)为100,数组中每个元素都会随机分配内存(随机数据),且数组长度无法修改,只通过修改length的值来限制数组元素访问。像js、python等等之类的语言无非是将底层数据结构做了包装吧。
实现目标(对应js中array对象的部分内建函数实现):
1.创建数组2.删除数组3.显示数组每个元素4.获取数组指定位子的元素5.查找元素6.指定位子插入元素7.删除数组中指定元素
void CreateList(SqList *&L, ElemType a[], int n); // 建立顺序表 void DestroyList(SqList *&L); void ListEmpty(SqList *L); int ListLength(SqList *L); void DispList(SqList *L); // 显示数组每哥元素 bool GetElem(SqList *L, int i, ElemType &e); // 求某个位置数据元素的值(1开始) int LocateElem(SqList *L, ElemType e); // 查找元素 bool ListInsert(SqList *&L, int i, ElemType e); // 插入元素(让第i个位置开始的所有元素一起后移) bool ListDelete(SqList *&L, int i, ElemType &e); // 删除元素
部分代码:
#include <stdio.h>#include <stdlib.h>#define MAX_SIZE 100typedef int ElemType;typedef struct{ ElemType data[MAX_SIZE]; int length;}SqList;int main() { printf("start\n"); SqList *L = NULL; int n = 5; ElemType arr[5] = {1, 2, 3, 4, 5}; ElemType newArr[5] = {7, 8, 9, 10, 6}; CreateList(L, newArr, n); DispList(L); ListLength(L); ElemType result = 0; GetElem(L, 1, result); printf("GetElem: %d\n", result); int locate = -1; locate = LocateElem(L, 4); printf("locate: %d\n", locate); ListInsert(L, 1, 1); DispList(L); ElemType delResult = -1; ListDelete(L, 4, delResult); DispList(L); printf("del: %d\n", delResult); return 0;}void CreateList(SqList *&L, ElemType a[], int n) { L = (SqList *)malloc(sizeof(SqList)); for (int i = 0; i < n; i++) { L->data[i] = a[i]; }; L->length = n;}void DispList(SqList *L) { for (int i = 0; i < L->length; i++) { printf("index: %d, value: %d;\n", i, L->data[i]); }; printf("\n");}int ListLength(SqList *L) { printf("length: %d\n", L->length); return L->length;}bool GetElem(SqList *L, int i, ElemType &e) { if (i <= 0 || i > L->length) { return false; } e = L->data[i - 1]; return true;}int LocateElem(SqList *L, ElemType e) { ElemType result = -1; for (int i = 0; i < L->length; i++) { if (L->data[i] == e) { result = i; break; } } return result;}bool ListInsert(SqList *&L, int i, ElemType e) { int realIndex = i - 1; if (realIndex < 0 || realIndex > L->length) { return false; } L->length++; for (int index = L->length; index > realIndex && index > 0; --index) { L->data[index] = L->data[index - 1]; } L->data[realIndex] = e; return true;}bool ListDelete(SqList *&L, int i, ElemType &e) { if (i < 0 || i >= L->length) { return false; } e = L->data[i - 1]; L->length--; for (int index = i - 1; index < L->length; index++) { L->data[index] = L->data[index + 1]; } return true;}