数据结构顺序表基本操作的实现
时间: 2023-05-11 19:02:26 浏览: 114
数据结构--顺序表的基本操作(C语言实现).docx
顺序表是一种线性表,它的基本操作包括插入、删除、查找、修改等。以下是顺序表基本操作的实现:
1. 初始化顺序表
void InitList(SqList &L)
{
L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem) exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
}
2. 插入元素
Status ListInsert(SqList &L, int i, ElemType e)
{
if (i < 1 || i > L.length + 1) return ERROR;
if (L.length >= L.listsize)
{
ElemType* newbase = (ElemType*)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase) exit(OVERFLOW);
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
ElemType* q = &(L.elem[i - 1]);
for (ElemType* p = &(L.elem[L.length - 1]); p >= q; --p) *(p + 1) = *p;
*q = e;
++L.length;
return OK;
}
3. 删除元素
Status ListDelete(SqList &L, int i, ElemType &e)
{
if (i < 1 || i > L.length) return ERROR;
ElemType* p = &(L.elem[i - 1]);
e = *p;
ElemType* q = L.elem + L.length - 1;
for (++p; p <= q; ++p) *(p - 1) = *p;
--L.length;
return OK;
}
4. 查找元素
int LocateElem(SqList L, ElemType e)
{
ElemType* p = L.elem;
for (int i = 1; i <= L.length; ++i, ++p) if (*p == e) return i;
return 0;
}
5. 修改元素
Status ListModify(SqList &L, int i, ElemType e)
{
if (i < 1 || i > L.length) return ERROR;
L.elem[i - 1] = e;
return OK;
}
以上就是顺序表基本操作的实现。
阅读全文