// 初始化顺序表L Status InitList_Sq(SqList &L, int size, int inc); // 销毁顺序表L voidDestroyList_Sq(SqList &L); // 将顺序表L清空 Status ClearList_Sq(SqList &L); // 判断顺序表是否为空,是返回 TRUE, 否则返回 FALSE Status ListEmpty_Sq(SqList L); // 返回顺序表L中元素个数 intListLength_Sq(SqList L); // 用e返回顺序表L中第i个元素的值 Status GetElem_Sq(SqList L, int i, ElemType &e); // 在顺序表L中查找元素e,查找成功返回该元素在表中第一次出现位置,否则返回-1 intSearch_Sq(SqList, ElemType e); // 遍历顺序表L, 依次对每个元素调用visit() Status ListTraverse_Sq(SqList L, Status( *visit)(ElemType e)); // 将顺序表L中第i个元素赋值为e Status PutElem_Sq(SqList &L, int i, ElemType e); // 在顺序表L表尾添加元素e Status Append_Sq(SqList &L, ElemType e); // 删除顺序表L表尾元素,并用e返回 Status DeleteLast_Sq(SqList &L, ElemType &e); // 在顺序表第i个元素之前插入新的元素e,表长加1 Status InsertList_Sq(SqList &L, int i, ElemType e); // 删除顺序表的第i个元素,返回到e,表长减1 Status DelElem_Sq(SqList &L, int i, ElemType &e);
顺序表接口实现
初始化顺序表
分配存储空间
给定顺序表容量
给定扩容增量
1 2 3 4 5 6 7 8 9 10
Status InitList_Sq(SqList &L, int size, int inc) { L.base = (ElemType*)malloc(size * sizeof(ElemType)); if (NULL == L.base) return OVERFLOW; L.size = size; L.increment = inc;
return OK; }
销毁顺序表
1 2 3 4
voidDestroyList_Sq(SqList &L) { free(L.base); }
将顺序表清空
1 2 3 4
voidClearList_Sq(SqList &L) { L.length = 0; }
判断顺序表是否为空
1 2 3 4 5 6 7
Status ListEmpty_Sq(SqList L) { if (L.length == 0) return TRUE; else return FALSE; }
求顺序表元素个数
1 2 3 4
intListLength_Sq(SqList L) { return L.length; }
求第 i 个元素值
1 2 3 4 5 6 7 8
Status GetElem_Sq(SqList L, int i, ElemType &e) { if (i < 0 || i > L.length) return ERROR; e = L.base[i - 1];
return OK; }
顺序查找
1 2 3 4 5 6 7 8 9 10
intSearch_Sq(SqList L, ElemType e) { int i = 0; while (i < L.length && L.elem[i] != e) i++; if (i < L.length) return i; else return ERROR; }
访问每个元素
1 2 3 4 5 6 7 8 9 10 11 12 13
status ListTraverse_Sq(SqList L, Status(*visit)(ElemType e)) { int i;
if (L == NULL || L.length <= 0) return ERROR;
for (i = 0; i < L.length; i++) { visit(L.base[i]); }
return OK; }
赋值指定位序元素
1 2 3 4 5 6 7 8 9
Status PutElem_Sq(SqList &L, int i, ElemType e) { if (i > L.length || L == NULL) return ERROR;
Status InsertList_Sq(SqList &L, int i, ElemType e) { int k; if (i < 1 || i > (L.length + 1)) return ERROR; if (L.>length == L.>size) { newbase = (ElemType*)realloc(L.base, (L.size + L.increcement) * sizeof(ElemType)); if (NULL == newbase) return OVERFLOW; L.base = newbase; L.size += L.increcement; } if (i < L.length + 1) for (k = L.length - 1; k > i - 1; k--) L.base[k] = L.base[k - 1]; L.base[i - 1] = e; L.lenght++; return OK; }
删除元素
时间复杂度:\(O(n)\)
判断参数i是否合法
判断表是否非空
取出删除元素
从被删元素位置开始向后遍历至最后一个元素,往前挪动一位
表长 - 1
同样地,删除元素也需要移动数组元素,故如需频繁删除元素,也应避免考虑顺序表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Status DelElem_Sq(SqList &L, int i, ElemType &e) { int k; if (i < 1 || i > L.length) return ERROR; if (L.length == 0) return ERROR; if (i < L.lengh) for (k = i - 1; k < L.length - 1; k++) L.base[k] = L.base[k + 1]; L.length--; return OK; }