编程实现线性表顺序存储下的基本操作: 1.初始化 2.插入元素 3.删除元素 4.获取第i个元素 5.判断元素是否存在---前面5个已提供源码参考 6.获取某个元素的下一个元素;NextElem(L, cur_e, &next_e); 7.获取某个元素的前一个元素;PriorElem(L, cur_e, &pre_e);C语言
时间: 2023-05-26 11:03:26 浏览: 92
next_e)
/* 初始化线性表 */
Status InitList(SqList &L)
{
L.elem = (ElemType*) malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem) return ERROR;
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}
/* 在线性表中插入元素 */
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 + LIST_INCREMENT) * sizeof(ElemType));
if (!newbase) return ERROR;
L.elem = newbase;
L.listsize += LIST_INCREMENT;
}
ElemType* p = &L.elem[i-1];
ElemType* q = &L.elem[L.length-1];
for (; q >= p; --q) *(q+1) = *q;
*p = e;
++L.length;
return OK;
}
/* 在线性表中删除元素 */
Status ListDelete(SqList &L, int i)
{
if (i < 1 || i > L.length) return ERROR;
ElemType* p = &L.elem[i-1];
ElemType* q = &L.elem[L.length-1];
for (++p; p <= q; ++p) *(p-1) = *p;
--L.length;
return OK;
}
/* 获取线性表中第i个元素 */
Status GetElem(SqList L, int i, ElemType &e)
{
if (i < 1 || i > L.length) return ERROR;
e = L.elem[i-1];
return OK;
}
/* 判断元素是否存在 */
int LocateElem(SqList L, ElemType e)
{
for(int i = 0; i < L.length; ++i)
if (e == L.elem[i])
return i+1;
return 0;
}
/* 获取某个元素的下一个元素 */
Status NextElem(SqList L, ElemType cur_e, ElemType &next_e)
{
int i = 0;
for(; i < L.length; ++i)
if (cur_e == L.elem[i])
break;
if (i == L.length) return ERROR;
if (i == L.length-1) return ERROR;
next_e = L.elem[i+1];
return OK;
}
阅读全文